用vue-cli新建的項目中要實現某些頁面禁用物理返回鍵,可使用以下的方法:
方法一:
在main.js中加上以下代碼作爲禁用路由判斷的依據:
const history = window.sessionStorage
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)
router.beforeEach(function (to, from, next) {
if (!store.getters.routerFlag) { // 禁用路由返回,保存到vuex內的
next(false)
return
}
})
store.getters.routerFlag默認是true,使用禁用路由返回時,把store.getters.routerFlag賦值爲false,切記在具體某頁面使用禁用路由的操作時需要在離開時重新賦值爲true,以免影響別的頁面使用物理返回鍵的操作。
在使用頁面給vuex的routerFlag賦值:
在script內引用了vuex:
import store from '../../vuex/store.j
使用時:
store.commit('UPDATE_ROUTERFLAG',false)
在跳出該頁面時,重新給routerFlag賦值以免影響別的頁面的物理返回鍵的使用:
store.commit('UPDATE_ROUTERFLAG',true)
以上方法只是禁用了物理返回鍵,如果需要監聽到點擊物理返回鍵進行操作時,則可以使用下面的方法:
方法二:
在具體使用禁用物理返回鍵的頁面添加如下代碼:
mounted() {
// 如果支持 popstate (一般移動端都支持)
if (window.history && window.history.pushState) {
// 往歷史記錄裏面添加一條新的當前頁面的url
history.pushState(null, null, document.URL);
// 給 popstate 綁定一個方法 監聽頁面刷新
window.addEventListener('popstate', this.backNative
, false);//false阻止默認事件
}
},
destroyed(){
window.removeEventListener('popstate', this.backNative
, false);//false阻止默認事件
},
methods:{
//返回
goBack(){
window.location.href = 'backtonative.html';//返回操作
},
goOrderDetail(){
store.commit('UPDATE_ROUTERFLAG',true)
let orderid = JSON.parse(decodeURIComponent(this.$route.params.orderid)).orderid;
this.$router.push(`/orderdetail/${orderid}`);
},
goIndex(){
window.location.href = 'backtonative.html';
},
backNative() {
console.log("監聽到了");
//點擊物理返回鍵要執行的操作
window.location.href = 'backtonative.html';
}
},
注:方法一比較適用於禁用物理返回鍵,即點擊物理返回鍵時不進行任何的操作,方法二除了適用於方法一的操作外,還適用於點擊物理返回鍵時進行制定操作的情況。