路由参数变动的探讨
在应用中利用路由参数,例如从路径 /user/foo
转向 /user/bar
,原有的组件实例会被重用以提高效率,因为这两个路径共享同一组件。此机制虽提升了性能,但也意味着组件的生命周期钩子将不再触发,需要另寻他径监控此类变化。
监视路由参数变更策略
策略一:利用 Watcher 监听
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); }},
实践案例
id
变化时触发初始化数据加载。watch: { '$route'(to, from) { if (to.query.id !== from.query.id) { this.id = to.query.id; this.init(); // 重新加载数据 } }},
init
方法。watch: { '$route': { handler: 'init', immediate: true }}
为了确保组件根据路由参数变化重新渲染,可为 <router-view>
添加唯一 key
,如使用 $route.fullPath
。
<router-view :key="$route.fullPath"></router-view>
策略二:应用导航守卫
next(vm => {})
访问实例。beforeRouteEnter(to, from, next) { console.log('进入前守卫触发'); next(vm => { console.log('组件实例:', vm); });},
beforeRouteUpdate(to, from, next) { console.log('路由更新守卫触发'); next();},
beforeRouteLeave(to, from, next) { const isConfirmed = window.confirm('确定离开此页?'); if (isConfirmed) { console.log('离开路由守卫确认离开'); next(); } else { next(false); // 阻止导航 }},
以上方法确保了路由参数变化时,无论是通过监听还是守卫机制,都能有效地响应并执行相应的逻辑处理。