項目中遇到如下需求
- 數據錄入頁面 , 用戶沒有保存數據的時候, 發生路由跳轉, 瀏覽器返回 時加以阻止 , 並給出提示 , 詢問未保存, 是否離開頁面
- 點擊保存以后 , 可以返回 , 自動跳轉 , 進入下一個頁面不加限制
實現過程 : 兩個方面入手 ,
- 瀏覽器返回功能 , 需要處理,
- vue-router 需要處理
實現方法(兩者結合)
瀏覽器返回處理方式
// mounted()的時候我們調用原生js , 操作一下history
history.pushState(null, null, document.URL); // 主要是在不刷新瀏覽器的情況下,創建新的瀏覽記錄並插入瀏覽記錄隊列中。 這步非常重要 , 不然的話當我們點擊返回按鈕 , 雖然頁面阻止了跳轉 , 但是url地址欄卻發生了變化 window.onpopstate = function (event) { // alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); history.pushState(null, null, document.URL);
//使用element that .$confirm("離開頁面 , bom將不做保存, 請確認已經保存", "提示", { confirmButtonText: "確定", cancelButtonText: "取消", type: "warning", }) .then(() => { that.deleteFile();//業務功能 , 可以忽略 that.$router.push({ name: "跳轉到頁面的name", params: { status: true } });//此處手動增加了狀態 , 主要為了監聽路由跳轉的時候判斷是否進行跳轉 , 看下面代碼 }) .catch(() => { // alert("window") return false; }); };
vue-router的處理方式
// vue路由的鈎子函數 , 可以放在mouted的同級
beforeRouteLeave(to, from, next) { console.log(to); console.log(from); if (to.params.status) {//就是上面的狀態 如果是true , 則不詢問是否保存, 當然這個方法比較笨, 大家可以使用更優雅的方式 next(); } else { this.$confirm("離開頁面 , bom將不做保存, 請確認已經保存", "提示", { confirmButtonText: "確定", cancelButtonText: "取消", type: "warning", }) .then(() => { this.deleteFile();//業務功能請忽略 next(); }) .catch(() => { // alert("router") }); } },
基本上就實現了 , 沒有經過測試 , 具體的bug以后有問題再修改吧