以前對于動態(tài)組件的切換窘问,都是在index.vue下的子組件中通過this.$parent.方法名
辆童,來直接調(diào)用父組件的方法實現(xiàn)組件切換,在vue中是不提倡這樣使用的惠赫“鸭可以使用this.$emit('方法名',{參數(shù)})
儿咱,將事件綁定在父組件上面來使用庭砍。
image.png
另一種方法便是我要說的,通過vue路由來實現(xiàn)動態(tài)組件的切換混埠。在上面index.vue文件中包含動態(tài)組件list怠缸、edit、add三個組件钳宪,每個組件代表一個頁面揭北,頁面加載后的默認(rèn)組件是list,edit和add都是通過list頁面進(jìn)入吏颖。(動態(tài)組件的切換是在index中實現(xiàn))
在list頁面代碼
methods: {
handleEdit() ·
this.$router.push({
query: {
pagination: "edit",
id: "0001",
},
}).catch(err =>{});e
},
},
使用this.$router.push()
方法傳遞參數(shù)pagination(跳轉(zhuǎn)頁面)搔体、id(其他參數(shù)),調(diào)用方法handleEdit在地址欄能看到傳的參數(shù)
image.png
在index頁面代碼
<template>
<div>
<component v-bind:is="currentTabComponent"></component>
</div>
</template>
<script>
import edit from "./edit";
import list from "./list";
export default {
data() {
return {
currentTabComponent: list,
};
},
watch: {
$route(route) {
this.handlerouter();
},
},
created() {
this.handlerouter();
},
components: {
edit,
list,
},
methods: {
handlerouter() {
const { query } = this.$route;
const { pagination, id } = query;
if (!pagination) return this.currentTabComponent = list;
switch (pagination) {
case "edit":
this.currentTabComponent = edit;
break;
default:
this.currentTabComponent = list;
}
},
},
};
</script>
在handlerouter()
方法中半醉,通過es6語法取得參數(shù)pagination疚俱、id,判斷pagination不存在或為空時組件為list頁面并跳出方法奉呛,有pagination時计螺,通過switch判斷來切換組件。
通過watch監(jiān)聽器來監(jiān)聽$route()
方法=》監(jiān)聽路由瞧壮,當(dāng)list調(diào)用handleEdit()發(fā)生路由跳轉(zhuǎn)登馒,就會被監(jiān)聽到,執(zhí)行this.handlerouter()
方法咆槽。
當(dāng)在edit頁面進(jìn)行瀏覽器刷新陈轿,參數(shù)pagination、id并不會被銷毀秦忿,但頁面刷新后會重新渲染執(zhí)行created()
方法麦射,在其中調(diào)用 this.handlerouter()
,便能實現(xiàn)頁面頁面刷新后還是edit頁面了灯谣。
點個贊再走吧G鼻铩!胎许!