Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!