Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda