方法一
使用window.history.pushState拦截返回键,在开启弹框时返回需要再添加一次历史记录。
页面一进来的时候,在mounted中就添加一个历史记录并监听返回键是否触发,给window添加一个popstate事件,拦截返回键,执行this.onBrowserBack事件。
因为vue不会刷新页面,所以必须在页面销毁时移除监听事件,否则会重复执行这个事件。
mounted() {
window.history.pushState(null, null, document.URL);
// addEventListener需要指向一个方法
window.addEventListener("popstate", this.onBrowserBack, false);
},
beforeUnmount() {
window.removeEventListener("popstate", this.onBrowserBack, false);
},
methods: {
onBrowserBack() {
if (this.dialogFormVisible) {
this.dialogFormVisible = true;
window.history.pushState(null, null, document.URL);
} else {
this.$router.go(-1);
}
},
}
方法二
推荐在beforeRouteLeave中判断弹框是否开启,但beforeRouteLeave只能在路由组件中使用
beforeRouteLeave(to, from, next) {
if (this.dialogFormVisible) {
next(false);
return;
}
next();
},