效果
关闭浏览器或关闭浏览器标签页时,弹窗提示是否确定关闭浏览器
Vue3选项式代码
export default {
name: 'YourComponentName',
mounted() {
// 当组件挂载时添加'beforeunload'事件监听器
window.addEventListener('beforeunload', this.handleBeforeUnload);
},
beforeUnmount() {
// 在组件卸载前移除事件监听器以避免内存泄漏
window.removeEventListener('beforeunload', this.handleBeforeUnload);
},
methods: {
handleBeforeUnload(event) {
// 给出一个提示信息,告知用户有未保存的数据或者询问用户是否真的想离开页面
const message = "您有未保存的更改,确定要离开吗?";
event.returnValue = message; // 标准写法,用于大多数现代浏览器
// 对于一些旧版浏览器,返回字符串作为提示信息
return message;
}
}
}