今天测试给我报了个bug说点击浏览器返回页数据显示的不对,我查了半天原因:需要监听浏览器的回退按钮,并阻止其默认事件。具体操作方法如下:具体操作方法如下:1、挂载完成后,判断浏览器是否支持popstate
mounted(){

if (window.history && window.history.pushState) {

history.pushState(null, null, document.URL);

window.addEventListener('popstate', this.cancel, false);
}
},
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);
}
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);

}

},
cancel: function() {

if(this.orderId){

this.$router.push({

name:"orderList",

params: {id:this.orderId},

});

}else{

this.$router.go(-1);

}

},补充知识:vue-router组件内导航守卫判断返回按钮补充知识:补充知识: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)
setTimeout(() => {

this.$confirm('编辑的页面布局尚未保存,确定离开?', '提示', {

confirmButtonText: '确定',

cancelButtonText: '取消',

type: 'warning'

}).then(() => {

next()

return

}).catch(() => {

this.$message({

type: 'info',

message: '已取消'

})

next(false)

return

})
}, 500)以上这篇vue监听浏览器原生返回按钮,进行路由转跳操作就是小编分享给大家的全部内容了,希望能给大家一个参考。