在项目中会经常遇到编辑页面的途中想要离开,如何提示用户,“此页面未保存,确定离开吗?”
在Vue Router 导航守卫中有一个组件内守卫:beforeRouteLeave
用法:
beforeRouteLeave (to, from , next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
next(false)
}
}
当用户编辑途中离开时,浏览器会跳出弹窗,提示用户是否离开(提示框为浏览器自带的提示框)。
如果使用框架,想要使用框架组件做提示的话,如下所示:
element ui+vue.js 做用户未保存修改离开提示
beforeRouteLeave(to, from, next) {
if (this.clickNextBtn) {//如果页面未修改,直接跳转,不弹出提示
next();
} else if (this.isCanSubmit) { //如果已经保存页面了,不弹出提示
next();
} else {
this.$confirm(//自定义提示弹窗
"You have unsaved changes in this page. Do you want to leave without saving?",
{
cancelButtonText: "Cancel",
confirmButtonText: "Yes",
closeClickModel: false
}
)
.then(() => {
next();
})
.catch(() => {
next(false);
});
}
},
样式如图: