在項(xiàng)目中會經(jīng)常遇到編輯頁面的途中想要離開体斩,如何提示用戶猜欺,“此頁面未保存晚伙,確定離開嗎吮龄?”
在Vue Router 導(dǎo)航守衛(wèi)中有一個組件內(nèi)守衛(wèi):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)
}
}
當(dāng)用戶編輯途中離開時,瀏覽器會跳出彈窗咆疗,提示用戶是否離開(提示框?yàn)闉g覽器自帶的提示框)漓帚。
如果使用框架,想要使用框架組件做提示的話午磁,如下所示:
element ui+vue.js 做用戶未保存修改離開提示
beforeRouteLeave(to, from, next) {
if (this.clickNextBtn) {//如果頁面未修改尝抖,直接跳轉(zhuǎn)毡们,不彈出提示
next();
} else if (this.isCanSubmit) { //如果已經(jīng)保存頁面了,不彈出提示
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);
});
}
},
樣式如圖:
1.png