I try to use dynamic component to update my section.
But, when i click on my sidebar (‘nav’), it dont change.
route.params.current change, but 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>
2
Answers
You can create a watcher for the
route
and on the callback function you can assign yourdynamicComponent
by passing any component name. In my case, I am watching forroute.name
(you can use any, as it is a basic example).But the trick here is to wait for the component to load as it is an asynchronous import. That’s how you can get the component easily.
Also use
shallowRef
instead ofref
when you definedynamicComponent
.shallowRef
will ensure that the component itself is not made reactive, only the reference to it.