vue項目中阻止瀏覽器左側返回鍵


某些頁面彈出提示框的時候,點擊返回鍵后隱藏提示框,而不是返回到上一個頁面。

mounted() {
  //頁面一進來的時候,就添加一個歷史記錄
  window.history.pushState(null, null, document.URL);
  // 給window添加一個popstate事件,攔截返回鍵,執行this.onBrowserBack事件,addEventListener需要指向一個方法
  window.addEventListener("popstate", this.onBrowserBack, false);
},
watch: {
  // 彈框監聽,當彈框顯示的時候,pushState添加一個歷史,供返回鍵使用
  PopupShow: {
    handler(newVal, oldVal) {
      if (newVal.Terms === true) {
        window.history.pushState(null, null, document.URL);
      }
    },
    deep: true
  }
},
 onBrowserBack() {
      // 比如判斷需求執行back()或者go(-2)或者PopupShow=false隱藏彈框
      if (this.isEdit && this.addDialogVisible) {
          this.$confirm('當前有沒有要編輯的內容,確定返回列表,將放棄本次操作', '提示', {
               confirmButtonText: '確定',
               cancelButtonText: '取消',
               type: 'warning'
          }).then(() => {
               if (this.isEdit && this.addDialogVisible) {
                   this.addDialogVisible = false
               }
               this.$router.go(-1)
           }).catch(() => {
               window.history.pushState(null, null, document.URL);
               console.log('1')
           });
       } else if (this.addDialogVisible2) {
           this.$confirm('當前有沒有要編輯的內容,確定返回列表,將放棄本次操作', '提示', {
               confirmButtonText: '確定',
               cancelButtonText: '取消',
               type: 'warning'
           }).then(() => {
               if (this.addDialogVisible2) {
                   this.$refs.contrast.delmodifysiteFns()
                   this.addDialogVisible = false
               }
               this.$router.go(-1)
           }).catch(() => {
               window.history.pushState(null, null, document.URL);
           });
       } else {
           this.$router.go(-1)
       }
   }
destroyed() {
  // 當頁面銷毀必須要移除這個事件,vue不刷新頁面,不移除會重復執行這個事件
  window.removeEventListener("popstate", this.onBrowserBack, false);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM