admin管理员组文章数量:1657737
注意:
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();
},
*如果对你有帮助,点个👍吧
版权声明:本文标题:vue监听手机物理返回键(浏览器返回) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1729797590a1212870.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论