需要监听手机的回退按钮。
1、挂载完成后,判断浏览器是否支持popstate
mounted(){
if (window.history && window.history.pushState) {
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.fun, false);//false阻止默认事件
}
},
2、页面销毁时,取消监听。否则其他vue路由页面也会被监听
destroyed(){
// 返回路径
window.removeEventListener('popstate', this.fun, false);//false阻止默认事件
},
3、将监听操作写在methods里面,removeEventListener取消监听内容必须跟开启监听保持一致,所以函数拿到methods里面写
methods:{
fun(){
history.pushState(null, null, location.href ); // 增加历史记录
console.log("监听到了");
}
}
// 安卓 物理键返回 健康
//拦截安卓回退按钮
history.pushState(null, null, location.href);
window.addEventListener('popstate', function(event) {
history.pushState(null, null, location.href ); // 添加 退出去 路径
//此处加入回退时你要执行的代码
});
其中location.href会自动获取到当前路径的url,添加到历史记录,然后每次点击都会先加入一次历史记录,然后再加入一次防止下次返回键触碰失效
好了,这样就能实现一种你想不让这个页面用户自己回退,或者返回键执行响应的方法,那么这个方法就很简单了。
ps:这个功能仅支持app中的,不带后退按钮的浏览器,也就是说页面中的返回按钮是我们自己写的事件那种。
参考:https://blog.csdn.net/qq_15238979/article/details/89242887
先介绍一下html5中history有哪些属性和API,我们用到了其中2个方法(pushState、replaceState),来根据状态存储的数据判断是否触发返回事件
1、window.history.length - 历史记录长度 (只读)
2、window.history.state - 历史记录状态 (只读)
3、window.history.go(num) - 回到指定的历史记录(参数num可以是正/负)
4、window.history.back() - 回到上一个历史记录
5、window.history.forward() - 回到下一个历史记录(前提当前历史记录不是最新的)
6、window.history.pushState(state, title, newUrl) - 新增一个历史记录(路径等于当前的url + newUrl )
7、window.history.replaceState(state, title, newUrl) - 替换当前的历史记录路径(路径等于当前的url + newUrl )
监听事件:window.onpopstate
502

被折叠的 条评论
为什么被折叠?



