vue 如何实现onshow
Vue 实现 onShow 生命周期的方法
在 Vue 中,没有直接对应小程序或原生应用中的 onShow 生命周期钩子,但可以通过以下方式模拟类似功能。
使用 Vue 的 mounted 和 activated 钩子
对于普通组件,mounted 钩子在组件首次加载时触发。若组件被 <keep-alive> 包裹,activated 钩子会在组件再次显示时触发。

export default {
mounted() {
this.handleShow();
},
activated() {
this.handleShow();
},
methods: {
handleShow() {
console.log('组件显示时触发');
}
}
}
监听路由变化
通过 Vue Router 的导航守卫或 $route 变化,可以判断页面是否显示。

export default {
watch: {
'$route'(to, from) {
if (to.path === '/current-page') {
this.handleShow();
}
}
},
methods: {
handleShow() {
console.log('页面显示时触发');
}
}
}
使用自定义事件
通过事件总线或 Vuex 触发显示事件。
// 事件总线方式
import Vue from 'vue';
const EventBus = new Vue();
export default {
created() {
EventBus.$on('page-show', this.handleShow);
},
beforeDestroy() {
EventBus.$off('page-show', this.handleShow);
},
methods: {
handleShow() {
console.log('页面显示时触发');
}
}
}
结合 Visibility API
监听浏览器标签页的可见性变化。
export default {
mounted() {
document.addEventListener('visibilitychange', this.handleVisibilityChange);
},
beforeDestroy() {
document.removeEventListener('visibilitychange', this.handleVisibilityChange);
},
methods: {
handleVisibilityChange() {
if (!document.hidden) {
this.handleShow();
}
},
handleShow() {
console.log('页面重新可见时触发');
}
}
}
适用场景建议
- 普通组件:使用
mounted和activated(配合<keep-alive>)。 - 页面级组件:结合 Vue Router 的路由监听。
- 跨组件通信:通过事件总线或状态管理工具。
- 浏览器标签页切换:使用 Visibility API。
根据具体需求选择合适的方法即可实现类似 onShow 的功能。






