在应用中利用路由参数,例如从路径 /user/foo 转向 /user/bar,原有的组件实例会被重用以提高效率,因为这两个路径共享同一组件。此机制虽提升了性能,但也意味着组件的生命周期钩子将不再触发,需要另寻他径监控此类变化。

方法一:直接在 watch 中定义对 $route 的监听,当路由变化时,自动执行对应的函数打印出新旧路由信息。
watch: {
$route(to, from) {
console.log('新路由:', to);
console.log('旧路由:', from);
}
},
方法二:采用更详细的配置,通过 handler 函数响应变更,并可设置 deep: true 进行深度监听
watch: {
$route: {
handler(to, from) {
console.log('新路由:', to);
console.log('旧路由:', from);
},
deep: true
}
},
方法三:绑定自定义方法处理路由变化,如 getPath。
watch: {
'$route': 'getPath'
},
methods: {
getPath(to, from) {
console.log('当前路由路径:', this.$route.path);
}
},
案例1:仅在查询参数 id 变化时触发初始化数据加载。
watch: {
'$route'(to, from) {
if (to.query.id !== from.query.id) {
this.id = to.query.id;
this.init(); // 重新加载数据
}
}
},
案例2:进入路由或路由参数变化时立即执行 init 方法。
watch: {
'$route': {
handler: 'init',
immediate: true
}
}
为了确保组件根据路由参数变化重新渲染,可为 <router-view> 添加唯一 key,如使用 $route.fullPath。
<router-view :key="$route.fullPath"></router-view>
策略二:应用导航守卫beforeRouteEnter:在组件渲染前调用,因此时组件实例未创建,需通过 next(vm => {}) 访问实例。
beforeRouteEnter(to, from, next) {
console.log('进入前守卫触发');
next(vm => {
console.log('组件实例:', vm);
});
},
beforeRouteUpdate:路由更新但组件复用时触发,可用于更新组件数据。
beforeRouteUpdate(to, from, next) {
console.log('路由更新守卫触发');
next();
},
beforeRouteLeave:离开当前路由前调用,可进行确认提示等操作。
beforeRouteLeave(to, from, next) {
const isConfirmed = window.confirm('确定离开此页?');
if (isConfirmed) {
console.log('离开路由守卫确认离开');
next();
} else {
next(false); // 阻止导航
}
},
以上方法确保了路由参数变化时,无论是通过监听还是守卫机制,都能有效地响应并执行相应的逻辑处理。