以前对于动态组件的切换,都是在index.vue下的子组件中通过this.$parent.方法名
,来直接调用父组件的方法实现组件切换,在vue中是不提倡这样使用的。可以使用this.$emit('方法名',{参数})
,将事件绑定在父组件上面来使用。
另一种方法便是我要说的,通过vue路由来实现动态组件的切换。在上面index.vue文件中包含动态组件list、edit、add三个组件,每个组件代表一个页面,页面加载后的默认组件是list,edit和add都是通过list页面进入。(动态组件的切换是在index中实现)
在list页面代码
methods: {
handleEdit() ·
this.$router.push({
query: {
pagination: "edit",
id: "0001",
},
}).catch(err =>{});e
},
},
使用this.$router.push()
方法传递参数pagination(跳转页面)、id(其他参数),调用方法handleEdit在地址栏能看到传的参数
在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语法取得参数pagination、id,判断pagination不存在或为空时组件为list页面并跳出方法,有pagination时,通过switch判断来切换组件。
通过watch监听器来监听$route()
方法=》监听路由,当list调用handleEdit()发生路由跳转,就会被监听到,执行this.handlerouter()
方法。
当在edit页面进行浏览器刷新,参数pagination、id并不会被销毁,但页面刷新后会重新渲染执行created()
方法,在其中调用 this.handlerouter()
,便能实现页面页面刷新后还是edit页面了。
点个赞再走吧!!!