vue监听手机物理返回键(浏览器返回)
vue监听手机物理返回键(浏览器返回),区分普通页面和缓存页面(keep-alive)
·
注意:
addEventListener和removeEventListener必须是同一个函数
区分普通页面和缓存页面(keep-alive)
//1、添加监听事件
mounted(){
if (window.history && window.history.pushState) {
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.goBack, false);
}
},
//2、监听事件返回路径
methods:{
goBack(){
this.$router.replace({path: '/'});
}
},
//3、页面销毁时,取消监听
destroyed(){
window.removeEventListener('popstate', this.goBack, false);
},
如果该页面是缓存页面,设置keep-alive之后,不会调用beforeDestroy和destroyed销毁生命周期函数,而是在生命周期函数中新增两个:activated和deactivated。
<keep-alive :include="Home">
<router-view :key="key" />
</keep-alive>
// 1、进入该页面时,会执行activated()函数
activated() {
if (window.history && window.history.pushState) {
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.goBack, false);
}
},
// 2、监听事件返回路径
methods:{
goBack(){
this.$router.replace({path: '/'});
}
注意:离开该页面时,销毁事件解决方法有2种 :
// 3、直接调用deactivated
deactivated() {
window.removeEventListener('popstate', this.goBack, false);
},
// 3、配合导航守卫,手动调用生命周期销毁函数
beforeRouteLeave (to, from, next) {
window.removeEventListener('popstate', this.goBack, false);
next();
},
*如果对你有帮助,点个👍吧
更多推荐
已为社区贡献1条内容
所有评论(0)