方法一:通过 watch
1.1 监听,当路由发生变化的时候执行
watch: {
$route(to, from) {
console.log(to.path);
}
},
1.2 监听,当路由发生变化的时候执行
watch: {
$route: {
handler: function(val, oldVal) {
console.log(val);
},
// 深度观察监听
deep: true
}
},
1.3 监听,当路由发生变化的时候执行
watch: {
$route: "getPath"
},
methods: {
getPath() {
console.log(this.$route.path);
}
},
方法二::key是用来阻止“复用”的。
Vue 为你提供了一种方式来声明“这两个元素是完全独立的——不要复用它们”。只需添加一个具有唯一值的 key 属性即可(Vue文档原话)
<router-view :key="key"></router-view>
使用computed属性和Date()可以保证每一次的key都是不同的,这样就可以如愿刷新数据了。
computed: {
key() {
return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date()
}
}