Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda