vue脚手架项目中使用vue-router时,在传递值时出现组件复用的解决方法
vue-router有两种传递值的方式,本案例只说编程式导航,(view-link的导航道理一样)
- 传值方式一(url?id)
- router.js文件
routes: [{
path: '/index',
component: Index,
children: [{
path: 'student',
component: Student
}, {
path: 'teacher',
component: Teacher
}]
}, {
path: '/login',
component: Login
}, ]
- 链接的文件
页面链接事件
<el-menu-item
v-for="(item, index) in num"
:key="index"
@click.self="router(index+1)"
>{{item}}班学生信息
</el-menu-item>
script:
export default {
data() {
return {
isCollapse: true,
num: ["一", "二", "三"]
};
},
methods: {
handleOpen(key, keyPath) {
console.log(key, keyPath);
},
handleClose(key, keyPath) {
console.log(key, keyPath);
},
router(id) {
console.log(id.toString());
this.$router.push({ path: '/index/student/', query: { id:id.toString() } })
}
}
};
- 传值方式二(url / : id)
- router.js文件
routes: [{
path: '/index',
component: Index,
children: [{
path: 'student/:id',
component: Student
}, {
path: 'teacher',
component: Teacher
}]
}, {
path: '/login',
component: Login
}, ]
- 链接的文件
页面链接事件
<el-menu-item
v-for="(item, index) in num"
:key="index"
@click.self="router(index+1)"
>{{item}}班学生信息
</el-menu-item>
script:
export default {
data() {
return {
isCollapse: true,
num: ["一", "二", "三"]
};
},
methods: {
handleOpen(key, keyPath) {
console.log(key, keyPath);
},
handleClose(key, keyPath) {
console.log(key, keyPath);
},
router(id) {
console.log(id.toString());
this.$router.push({ path: '/index/student/', params: { id:id.toString() } })
}
}
};
- 接收数据(student.vue文件中)
this.id = this.$route.query.id;
this.id = this.$route.params.id;
背景介绍完,到问题了
这个
这个!
这个!!
这个!!!最可恨
解决办法(问题:在使用Vue-router做项目时,会遇到如/serviceId/:id这样只改变id号的场景。由于router-view是复用的,单纯的改变id号并不会刷新router-view,而这并不是我们所期望的结果)
- 方法一:
可以尝试在组件中使用beforeRouteUpdate和beforeRouteLeave两个导航守卫函数来打印里面的to、from,会发现第一个函数正常打印,第二个函数根本不会执行,就是组件复用的结果。
2. 方法二:通过监听属性watch,监听$route的的变换