1. 程式人生 > 程式設計 >vue監聽瀏覽器原生返回按鈕,進行路由轉跳操作

vue監聽瀏覽器原生返回按鈕,進行路由轉跳操作

今天測試給我報了個bug說點選瀏覽器返回頁資料顯示的不對,我查了半天原因:需要監聽瀏覽器的回退按鈕,並阻止其預設事件。

具體操作方法如下:

1、掛載完成後,判斷瀏覽器是否支援popstate

mounted(){
   if (window.history && window.history.pushState) {
  history.pushState(null,null,document.URL);
  window.addEventListener('popstate',this.cancel,false);
 }
 },

2、頁面銷燬時,取消監聽。否則其他vue路由頁面也會被監聽

 destroyed(){
 window.removeEventListener('popstate',false);
 }

3、將監聽操作寫在methods裡面,removeEventListener取消監聽內容必須跟開啟監聽保持一致,所以函式拿到methods裡面寫

 cancel: function() {
   if(this.orderId){
     this.$router.push({
      name:"orderList",params: {id:this.orderId},});
   }else{
   this.$router.go(-1);
   }
  },

補充知識:vue-router元件內導航守衛判斷返回按鈕

元件內導航守衛會出現無法攔截$router.go(-1)或者物理返回按鈕,在攔截函式外包裹setTimeout即可。具體原因還未發現。

 setTimeout(() => {
  this.$confirm('編輯的頁面佈局尚未儲存,確定離開?','提示',{
   confirmButtonText: '確定',cancelButtonText: '取消',type: 'warning'
  }).then(() => {
   next()
   return
  }).catch(() => {
   this.$message({
    type: 'info',message: '已取消'
   })
   next(false)
   return
  })
 },500)

以上這篇vue監聽瀏覽器原生返回按鈕,進行路由轉跳操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。