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项目中在当前页面点击原生返回按钮不走历史路由直接回退(或者别的操作)
最新推荐文章于 2023-08-07 15:35:46 发布
该博客探讨了在Vue应用中如何利用浏览器的popstate事件和history API进行页面状态管理。通过在组件挂载时检测popstate支持并设置监听器,以及在组件销毁时移除监听,确保只对当前路由进行操作。当用户尝试回退时,依据订单ID存在与否,决定是跳转到订单列表还是返回上一页。这种方式强化了路由的安全性和用户体验。
1万+

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



