【开发笔记】VUE 框架实作介入使用者离开或关闭页面
Web app 虽然也是蜕变自 Web page,但是使用者与页面在交互上却是有很大的不同。例如离开或是关闭页面时,根据 App 运行的状况,给予适度的提醒来避免中断未完成的工作。
使用者离开页面时
在一般标准的情况,VUE 的页面跳转都是借由 Vue Router 来实现。因此透过导航守卫(Navigation Guards)可以很容易地拦截使用者离开页面的相关操作。
而拦截使用者离开页面的方式分为全域(例如:router.beforeEach),或是元件内的 Hooks 来实现。阿柴自己是比较偏好元件内的 beforeRouteLeave,因为逻辑上会比较单纯。
beforeRouteLeave(to, from, next) {
const count = this.items
.filter((item) => {
return !item.done || item.failed
}).length;
if (count > 0) {
const answer = window.confirm('确定要离开吗?');
if (!answer) {
return false;
}
}
next();
},
mounted() { ... },
created() { ... },
使用者关闭页面时
至于拦截使用者关闭页面的时机,阿柴试过了 beforeUnmount(3.0)和 beforeDestroy(2.x)都没有得到很好的效果。后来是透过订阅事件 beforeunload 来实现。
created() {
window.addEventListener("beforeunload", this.beforeWindowUnload);
},
beforeDestroy() {
window.removeEventListener("beforeunload", this.beforeWindowUnload);
},
methods: {
beforeWindowUnload(e) {
e.preventDefault();
e.returnValue = "";
},
}