我需要在點擊時在 Vue JS 中動態創建一個組件,然后路由到該組件。我正在使用 Vue 3。一切都需要一鍵完成。我的代碼看起來像這樣
methods:{
routerClick(value){
console.log("number is " value)
this.$router.push({path:'New', name:'New', component: ()=>Vue.component('New')})
}
},
我不需要移動已經創建的組件。我想在此方法中創建一個組件,然后使用此路由器路由到該組件。請,任何建議將不勝感激。
uj5u.com熱心網友回復:
下面是一個可行的簡單解決方案(我不是 Vue 3 的專家)。
重點是addRoute在推送之前使用,因為推送到路由時不能指定路由組件。
這是帶有作業解決方案的代碼框。
<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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466004.html
