需求是這樣的:用戶在編輯頁以及新增頁面時,如果用戶手動要跳轉到其它頁面,就出來一個彈窗提示用戶巴拉巴拉。。。
然後,使用vue的 beforeRouteLeave 路由守衛可以對一些路由操作進行跳轉前提示,但是如果用戶點了瀏覽器的後退按鈕,那這個路由守衛基本沒用了啊,那個彈窗就閃了一下就消失了,路由直接改變,但是頁面不刷新(寫這篇文章時,我在想,可能我的路由有問題,不然爲什麼路由變了,但是頁面不刷新?)
下面是代碼,在App.vue裏面添加:
mounted () {
if (window.history && window.history.pushState) {
history.pushState(null, null, document.URL)
window.addEventListener('popstate', this.goBack, false)
}
},
destroyed () {
window.removeEventListener('popstate', this.goBack, false)
},
methods: {
goBack () {
// 該事件僅在瀏覽器後退按鈕被點擊時觸發
let needCofirmRouter = ['/addPro']
console.log(document.URL.split('#')[1])
history.pushState(null, null, null)
if (needCofirmRouter.indexOf(document.URL.split('#')[1]) > -1) {
this.$confirm('請確認數據已保存,頁面跳轉後已填寫的數據會被清空,是否繼續跳轉?', '提示', {
confirmButtonText: '是',
cancelButtonText: '否',
type: 'warning'
}).then(() => {
// 這裏不可以使用back,go(-1)等方法,不然會再次觸發該事件進入死循環
// this.$router.go(-1)
}).catch((ms) => {
})
}
}
}