有一次在修改別人的代碼時,發(fā)現頁面一進來會加載兩次,導致要返回到上一頁面還要點兩次才能返回,找了原因,發(fā)現原來是axios發(fā)送了兩次請求(一次為請求方法為option,一次為正常請求),具體解釋請點查看,我一般用的是代理跨域,第一次遇到這種跨域處理,由于技術過渣不知道怎么改,只好想辦法控制返回事件實現點擊一次返回上一級(就是這么強硬 (~O~))
第二次更新,之前的使用onpopstate,沒有在頁面離開時候移除掉事件,導致其他頁面也觸發(fā),所以重新需要加下移除事件
//unit.js
// 存儲當前歷史記錄點,實現控制手機物理返回鍵的按鈕事件
export const pushHistory = () => {
let state = { title: '', url: '' }
window.history.pushState(state, state.title, state.url)
}
//index.vue
<script>
import { pushHistory } from '@/misc/utils' // 引入工具類
export default {
mounted () {
this.onpopstate()
},
methods: {
// 監(jiān)聽歷史記錄點, 添加返回事件監(jiān)聽
onpopstate () {
pushHistory()
// 給window添加一個popstate事件,攔截返回鍵,執(zhí)行this.closeViews事件,addEventListener需要指向一個方法
window.addEventListener("popstate", this.closeViews, false);
},
closeViews () {
this.$toast('退出程序')
}
},
destroyed () {
// 當頁面銷毀必須要移除這個事件,vue不刷新頁面,不移除會重復執(zhí)行這個事件
window.removeEventListener("popstate", this.closeViews, false);
}
}
</script>
注意
使用了頁面緩存,是不會執(zhí)行destroyed,之前有同事就出現這個問題卡住了,如果用了頁面緩存的,可以使用路由離開監(jiān)聽替換destroyed