"Experience the power of Vue.js 3.2 with Dynamic Component Knockout

I am trying to use a dynamic component to update my section, but when I click on my sidebar ('nav'), it doesn't change. Even though route.params.current changes, the component is not loaded.


<template>
  <q-page class="container q-py-lg">
    <div class="q-pa-md row q-gutter-md">
      
      <nav class="col">
        <ul>
          <li v-for="(link, i) in links" :key="i" :class="link.label === route.params.current ? 'active' : 'cursor-pointer'" @click="router.push({ name: 'settings', params: { current: link.label }})">
            <span><q-icon size="xs" class="icon q-mx-sm" :name="link.icon"></q-icon></span>
            <span>{{  t(link.label) }}</span>
          </li>
        </ul>
      </nav>

      <section class="col-xs-12 col-md-6 col-lg-9">
        <q-card flat class="bg-teal text-white">
          <q-card-section>
            <component :is="getComponent(route.params.current)"></component>
          </q-card-section>
        </q-card>
      </section>
    </div>
  </q-page>
</template>

<script setup>
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";

const { t } = useI18n();
const route = useRoute();
const router = useRouter();

const getComponent = (name) => import(`./Settings/${name}.vue`);

const links = [
  { label: "account", icon: "person" },
  { label: "gameBehavior", icon: "sports_esports" }
];

</script>

Answer №1

If you want to create a watcher for the route, you can set up a callback function that assigns your dynamicComponent by passing any component name. In my scenario, I am monitoring route.name (although this is just a basic example).

The key here is to be patient and wait for the component to load since it involves an asynchronous import process. This way, accessing the component becomes straightforward.

When defining dynamicComponent, consider using shallowRef instead of ref. By using shallowRef, only the reference to the component will be reactive, not the component itself.

To delve deeper into DynamicComponents, check out this resource: here

<template>
  <header>
    <nav>
      <RouterLink to="/">Home</RouterLink>
      <RouterLink to="/about">About</RouterLink>
    </nav>
  </header>

  <!-- Utilize the dynamicComponent variable as a component -->
  <component :is="dynamicComponent"></component>
</template>

<script lang="ts" setup>
import { RouterLink } from 'vue-router'
import { shallowRef, watch } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();

// When defining dynamicComponent, opt for shallowRef rather than ref.
// Using shallowRef guarantees that solely the reference to the component is made reactive, not the component itself.
const dynamicComponent = shallowRef<any>(null);

// Monitor changes in the route name within the router
// It's possible to monitor any property
watch(route, async () => {
  dynamicComponent.value = (await import(`./views/${route.name as string}View.vue`)).default;
});
</script>

Answer №2

<Component :is="loadComponent"></Component>
<script setup>
import {ref, defineAsyncComponent} from 'vue'
const componentName = ref(null)  // if you use it - define it
const loadComponent = computed(() => 
         defineAsyncComponent(() => import(`./Settings/${componentName.value}.vue`)
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JQuery and CSS can be used to create a div overlay without impacting the positions of other divs on the

Is there a way to make a div overlay other divs (like a dropdown list) without affecting the positions of other divs? I have a #hidden div that appears when you hover over a #HoverMe div, but it moves the position of other divs when hovered. How can I ...

The incorrect html encoding is being done by CKEditor

I inserted a test link as follows: <a href="https//example.com?test=5&sectid=4"/>testLink When I attempt to edit the link using ckeditor and right-click on it, the URL text box mistakenly converts "&sectid=4" to the section symbol § ...

Preventing Event Propagation in JQuery Across Different Web Browsers

My GUI controls have a complex nested structure, and I need to prevent events from propagating up the DOM tree when they are clicked or changed. This functionality must be consistent across all browsers. Currently, I am using some cumbersome JavaScript co ...

Utilizing Angular's $locationProvider.html5Mode in conjunction with $window parameters

Lately, I encountered some difficulties with Google indexing due to angular routing. After much trial and error, I discovered that using $locationProvider.html5Mode solved the issue. However, a new problem has arisen where $window variables lose their val ...

Answer processing for the reminder dialog is underway

When I send a proactive message to a user, I want to initiate a 'reminder dialog'. The dialog is displayed, but when processing the response it goes back to the main dialog. This is how I currently set up my bot: const conversationState = new C ...

JavaScript Function to Redirect Page After a Delay of X Seconds

I'm trying to implement a redirect to a specific URL after displaying an error message for 5 seconds. Initially, I used JavaScript like this: document.ready(window.setTimeout(location.href = "https://www.google.co.in",5000)); However, the redirectio ...

Guide to triggering a Vue.js function upon page loading using Vue 3.0 and Ant Design 2.1.2

My Vue project uses Vue 3.0.0 and Ant Design version 2.1.2. In my previous project with Vue 2.0, I had a function called "getScriptList" that automatically executed when placed in the component's "mounted" lifecycle hook. However, I'm struggling ...

Error encountered when attempting to create a new Vue project using Vue CLI (npm issue)

I'm having trouble creating a new Vue CLI project. It was working fine before, but now it's not working... Vue CLI v4.2.3 ✨ Creating project in /Web develop/Vue Projects/new. ...

What is the process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

What are some methods for extracting a value from a separate webpage and saving it as a variable in my code?

I am utilizing graphite to obtain statistics and would like to display a justgage gauge for a specific variable. Graphite provides values in either JSON format: [{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}] o ...

The Ajax call is failing to trigger the success function

Can anyone assist me? My success function isn't working properly. The beforesend is functioning correctly and I've verified the variable s. It has a true value before the ajax call, so all validations are correct. Please take a look... function ...

Discrepancy in handling dummy data versus database data

Currently, I am diving into the world of Node.js/Express and have encountered a rather peculiar issue. I suspect that at the core of it lies a misunderstanding of how arrays/objects are copied. Despite my research efforts, I seem to be stuck, so any insigh ...

Is it beneficial for performance to utilize JavaScript local variables intermittently?

Looking at these two sections of script, there is a slight difference in length and variable use. The first example is shorter by one line and uses one less variable $t, but it converts this into a jQuery object an extra time. Considering performance rath ...

The VueJS nested data structure

As a newcomer to VueJS, I am exploring how to nest or reference component properties within others to ensure that the v-model binding updates them correctly. An example of what I'm trying to achieve is illustrated below. Template: <table> ...

Utilize JSON text importing for template literals in Node.js

When it comes to my node js projects, I usually opt for using a text.json file and requiring it rather than hardcoding static text directly into my code. Here's an example: JSON file { "greet": "Hello world" } var text = require('./text.json ...

` Time Running Out: A Classy Countdown Timer`

Here are the lines of code I have included in my webpage - example/demo. HTML: <p class="countdown-timer">10:00</p> <p class="countdown-timer">10:00</p> JavaScript: I am looking for guidance as a beginner in JavaScript and JQue ...

trigger an event from a different event in Node.js

I am attempting to retrieve the list of newly connected users in admin.html client.html (client login authentication) admin.html (notify new user join) server.js app.get('/', function(req, res){ res.sendfile('client.html'); }); ap ...

This error is thrown when trying to access the property 'message' of an undefined value

I'm currently working on adding an AJAX contact form to my website. However, I've run into a problem where when I try to submit the form, I encounter the following error in Google Chrome: "Uncaught TypeError: Cannot read property 'message&a ...

In Vue3, have you ever wondered why the $emit function seems to work fine before a promise fetch,

https://i.sstatic.net/yJmDY.jpg I have encountered an issue while attempting to pass the result of a promise fetch from a child component to a parent component using emit. Strangely, the emit function was working perfectly fine before the $fetch operation, ...

How can AngularJS handle multiple views sharing the same controller and ensure that the controller is executed only once?

Currently, I am facing a situation where I have two separate views that I would like to control within a single controller. The issue is, the controller is being executed twice. Is there a way to link multiple views to the same controller without the cont ...