vue.js监听路由变化的方法:1、通过watch实现,代码为【watch:{$route(to,from){console.log(to.path);}】;2、key是用来阻止“复用”的,代码为【

本教程操作环境:windows10系统、vue2.9,本文适用于所有品牌的电脑。
【相关文章推荐:vue.js】
vue.js监听路由变化的方法:
方法一:通过 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);
}
}方法二:key是用来阻止“复用”的
Vue 为你提供了一种方式来声明“这两个元素是完全独立的——不要复用它们”。只需添加一个具有唯一值的 key 属性即可(Vue文档原话)
computed: { key() { return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date() } }
使用computed属性和Date()可以保证每一次的key都是不同的,这样就可以如愿刷新数据了。
方法三:通过 vue-router 的钩子函数 beforeRouteEnter beforeRouteUpdate beforeRouteLeave
相关免费学习推荐:JavaScript(视频)











