vue+vuex+router實現阻止瀏覽器回退


 

場景說明,如圖,首頁有個列表,點擊加號后,會彈出一個表單,希望實現在顯示表單后,點擊回退,不是改變路由或者返回前一頁,而是關閉彈出的表單。

 

 

 

index.vue(頁面) 和 form.vue(組件)

 

用vuex的store作為 頁面和組件的通信

 

import Vuex from 'Vuex'

const store = new Vuex.Store({
    state:{
        canBack: true
    },
    mutations:{
        allowBack: state => state.canBack = true,
        notAllowBack: state => {
            state.canBack = false
            history.pushState(null, null, location.href)
        }
    }
})

export default store;

  

 

index.vue 點擊加號事件中要,設置不能回退

  store.commit("notAllowBack");

 

然后讓組件顯示

 

form組件在mounted時添加window監聽(重點

// 必須用window.onpopstate 而不是 window.addEventListener,不然面不好清除   
window.onpopstate = event => { if (!store.state.canBack) { history.go(1); // 重點,這是阻止回退事件,要配合 store里的 history.pushState使用
      this.$emit("quite"); // 提交退出事件,讓外部處理
      }
    };

  

index.vue接收到關閉事件后處理

store.commit('allowBack'); // 狀態改變,改為可以后退
window.onpopstate =  event => {}; // 清除onpopstate事件,同上面一樣,不要使用addEventListener
this.formVisible = false;

  

 


免責聲明!

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



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