生活中只有两种选择:重新开始,成为自己生活的主角;或留在原处并成为他人的支持角色。生活中,很多时候都需要我们要耐心,耐心做人,耐心做事,更要耐心生活。
今天测试给我报了个bug说点击浏览器返回页数据显示的不对,我查了半天原因:需要监听浏览器的回退按钮,并阻止其默认事件。
具体操作方法如下:
1、挂载完成后,判断浏览器是否支持popstate
mounted(){
if (window.history && window.history.pushState) {
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.cancel, false);
}
},
2、页面销毁时,取消监听。否则其他vue路由页面也会被监听
destroyed(){
window.removeEventListener('popstate', this.cancel, false);
}
3、将监听操作写在methods里面,removeEventListener取消监听内容必须跟开启监听保持一致,所以函数拿到methods里面写
cancel: function() {
if(this.orderId){
this.$router.push({
name:"orderList",
params: {id:this.orderId},
});
}else{
this.$router.go(-1);
}
},
补充知识:vue-router组件内导航守卫判断返回按钮
组件内导航守卫会出现无法拦截$router.go(-1)或者物理返回按钮,在拦截函数外包裹setTimeout即可。具体原因还未发现。
setTimeout(() => {
this.$confirm('编辑的页面布局尚未保存,确定离开?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
next()
return
}).catch(() => {
this.$message({
type: 'info',
message: '已取消'
})
next(false)
return
})
}, 500)
以上这篇vue监听浏览器原生返回按钮,进行路由转跳操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。