vue router 实现onshow
Vue Router 实现 onShow 功能
在 Vue Router 中,没有直接提供 onShow 生命周期钩子,但可以通过以下几种方式模拟类似的功能。
使用 watch 监听路由变化
通过 watch 监听 $route 对象的变化,可以在路由进入时执行特定逻辑。
export default {
watch: {
'$route'(to, from) {
if (to.path === '/your-path') {
// 相当于 onShow 逻辑
console.log('页面显示');
}
}
}
}
使用导航守卫
在组件内使用 beforeRouteEnter 和 beforeRouteUpdate 守卫,结合 next 回调函数实现类似 onShow 的功能。
export default {
beforeRouteEnter(to, from, next) {
next(vm => {
// 相当于 onShow 逻辑
console.log('页面显示');
});
},
beforeRouteUpdate(to, from, next) {
// 相当于 onShow 逻辑
console.log('页面更新');
next();
}
}
使用 activated 生命周期钩子
如果组件被 <keep-alive> 缓存,可以使用 activated 生命周期钩子模拟 onShow 功能。
export default {
activated() {
// 相当于 onShow 逻辑
console.log('页面显示');
}
}
结合 mounted 和 $route 判断
在 mounted 钩子中结合当前路由判断是否执行 onShow 逻辑。
export default {
mounted() {
if (this.$route.path === '/your-path') {
// 相当于 onShow 逻辑
console.log('页面显示');
}
}
}
使用事件总线或 Vuex
通过事件总线或 Vuex 状态管理,在路由变化时触发全局事件。

// 在路由配置中
router.afterEach((to, from) => {
if (to.path === '/your-path') {
// 触发全局事件
eventBus.$emit('onShow');
}
});
// 在组件中
export default {
created() {
eventBus.$on('onShow', () => {
console.log('页面显示');
});
},
beforeDestroy() {
eventBus.$off('onShow');
}
}
以上方法可以根据具体需求选择使用,灵活实现类似 onShow 的功能。






