实际项目开发中有时候需要根据路由的变化去实进行一些操作,在此,我总结了三种方法。
1、watch监听
// 监听,当路由发生变化的时候执行
watch:{
$route(to,from){
console.log(to.path);
}
},
或者
// 监听,当路由发生变化的时候执行
watch: {
$route: {
handler: function(val, oldVal){
console.log(val);
},
// 深度观察监听
deep: true
}
},
或者
// 监听,当路由发生变化的时候执行
watch: {
'$route':'getPath'
},
methods: {
getPath(){
console.log(this.$route.path);
}
}
2、:key 阻止复用
vue 为你提供了一种方式来声明“这两个元素是完全独立的——不要复用它们”。只需添加一个具有唯一值的 key 属性即可(Vue文档原话)
使用computed属性和Date()可以保证每一次的key都是不同的,这样就可以如愿刷新数据了。
<router-view :key="key"></router-view>
computed: {
key() {
return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date()
}
}
3、vue-router 的钩子函数
<script>
export default {
name: 'app',
// 监听,当路由发生变化的时候执行
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当钩子执行前,组件实例还没被创建
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
}
</script>
使用场景:
点击页面内跳转按钮 导航菜单选中
在element中有个NavMenu 导航菜单 组件
在A菜单页面中,有一个按钮button组件,点击这个button跳转到B菜单页。虽然页面已经跳过去了,但是导航菜单的选中状态并没有发生改变,还在A菜单上面。也就是default-active
,还停留在A上。
此时就可以在导航菜单的组件中去监听router。方法如下:
data() {
return {
activeIndex: this.$route.path
};
},
watch:{
'$route'(to,from){
this.activeIndex=to.path
}
},
组件代码
<template>
<el-menu
router
theme="dark"
:default-active="activeIndex"
class="el-menu-demo"
active-text-color="rgb(250,83,83)"
mode="horizontal"
@select="handleSelect"
>
<el-menu-item index="/">首页</el-menu-item>
<el-menu-item index="/Material" >我要找</el-menu-item>
<el-menu-item index="/Workbench" >工作台</el-menu-item>
</el-menu>
</template>
<script>
export default {
data() {
return {
activeIndex: this.$route.path
};
},
watch:{
'$route'(to,from){
this.activeIndex=to.path
}
},
mounted(){
},
methods: {
handleSelect(key, keyPath) {
}
}
};
</script>