javascriptvue.jsvue-componentvuexvuejs-slots

Dynamically create a component in Vue JS


I need to create a component in Vue JS dynamically on click and then route to that component. I am using Vue 3. Everything needs to happen in one click. My code looks something like this

methods:{
  routerClick(value){
    console.log("number is "+value)
    this.$router.push({path:'New', name:'New', component: ()=>Vue.component('New')})
  }
},

I do not need to move a component that is already created. I want to create a component inside this method and then route to the component using this router. Please, any suggestions will be highly appreciated.


Solution

  • Below is a simplistic solution that works (I'm not an expert in Vue 3).

    The main point is to use addRoute before pushing to it, because you cannot specify the route component when pushing to a route.

    Here is the codesandbox with the working solution.

     <template>
      <router-link to="/">Home</router-link>
      <button @click="createComponent">Create Component</button>
    
      <router-view></router-view>
    </template>
    
    <script>
    import { getCurrentInstance } from "vue";
    import { useRouter } from "vue-router";
    export default {
      name: "App",
      setup() {
        const app = getCurrentInstance().appContext.app;
        const router = useRouter();
    
        const createComponent = () => {
          // Check if the component has been alreadey registered
          if (!app.component("NewComponent")) {
            app.component("NewComponent", {
              name: "NewComponent",
              template: `<div>This is a new component</div>`
            });
          }
    
          const newComponent = app.component("NewComponent");
          // Adding a new route to the new component
          router.addRoute({ path: "/new", component: newComponent });
    
          router.push("/new");
        };
        return {
          createComponent,
        };
      },
    };
    </script>