[Vuejs]-Vuejs 3.2 Dynamic Component KO

0👍

You can create a watcher for the route and on the callback function you can assign your dynamicComponent by passing any component name. In my case, I am watching for route.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 of ref when you define dynamicComponent. shallowRef will ensure that the component itself is not made reactive, only the reference to it.

Learn more about DynamicComponents here

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

  <!-- Pass the dynamicComponent variable as 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();

// Use shallowRef instead of ref when you define dynamicComponent.
// shallowRef will ensure that the component itself is not made reactive,
// only the reference to it.
const dynamicComponent = shallowRef<any>(null);

// Watch for the change in the route name in the router
// You can watch any property
watch(route, async () => {
  dynamicComponent.value = (await import(`./views/${route.name as string}View.vue`)).default;
});
</script>

0👍

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

Leave a comment