在H5項(xiàng)目中螟蝙,需要控制手機(jī)返回按鈕葡秒,在網(wǎng)上找了很多資料斯入,發(fā)現(xiàn)用的最多的是:
“history popstate” 實(shí)現(xiàn)肌索,經(jīng)過觀察蕉拢,發(fā)現(xiàn)和beforeRouterLeave方法 效果是一樣的。
history popstate 方式:
//掛載完成后,判斷瀏覽器是否支持popstate
mounted(){
if (window.history && window.history.pushState) {
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.cancel, false);
}
},
//頁面銷毀時(shí)晕换,取消監(jiān)聽午乓。否則其他vue路由頁面也會(huì)被監(jiān)聽
destroyed(){
window.removeEventListener('popstate', this.cancel, false);
}
//具體的處理方式
cancel: function() {
if(this.orderId){
this.$router.push({
name:"orderList",
params: {id:this.orderId},
});
}else{
this.$router.go(-1);
}
},
這種方式,主要控制當(dāng)用戶點(diǎn)擊返回按鈕時(shí)闸准,該做如何處理益愈,針對(duì)不同的路由 和需要返回的路由 需要自己做判斷。
這種方式和beforeRouteLeave其實(shí)是一樣的都是在用戶點(diǎn)擊返回按鈕時(shí)夷家,做處理蒸其,不管哪種方式都需要自己針對(duì)不同的路由寫具體的邏輯,真是有點(diǎn)麻煩翱饪臁C!义屏!
我最終選擇利用router中的 beforeRouteLeave 結(jié)合router中push replace go 實(shí)現(xiàn)靠汁。
首先需要了解 vue-router中路由轉(zhuǎn)換的方式,可參考vue-router官網(wǎng)闽铐。
vue-route路由轉(zhuǎn)換 一般 通過以下3種方式:
router.push() //轉(zhuǎn)換路由 會(huì)向history中增加路由
router.replace() //替換當(dāng)前路由 此時(shí)history中當(dāng)前路由是被替換后的路由
router.go(n) //在 history 記錄中向前或者后退多少步蝶怔,類似window.history.go(n)。
主要思想就是針對(duì)不同路由自己做邏輯處理:
貼段代碼:
需求是:從列表頁和首頁都能跳轉(zhuǎn)詳情頁兄墅,詳情頁跳轉(zhuǎn)寫評(píng)論頁添谊,從寫評(píng)論跳轉(zhuǎn)到詳情頁,需要攜帶該詳情的數(shù)據(jù)察迟。所以需要將數(shù)據(jù)傳到detail中
beforeRouteLeave(to, from, next) {
if (to.name === 'detail') {
to.query.items = this.list
}
next()
// next({path: '/detail'})
},
想要判斷從哪個(gè)路由跳轉(zhuǎn)進(jìn)來斩狱,可以在from頁面添加標(biāo)識(shí)符,然后在該頁面使用 watch監(jiān)聽數(shù)據(jù)扎瓶,
//from頁面
goDetail() {
this.$router.replace({
path: '/detail',
query: {
items: this.list,
isFromComment: true
}
})
},
//to頁面
watch: {
$route: {
handler: function(route) {
// 從寫評(píng)論頁返回
if (route.query.isFromComment) {
this.isFromComment = true
}
},
immediate: true // 立即執(zhí)行所踊,而不是等到有變化時(shí)才執(zhí)行
}
}
然后自己再處理邏輯,整體思路是以上這樣概荷,具體的邏輯跟需求相關(guān)秕岛。
以上是我一個(gè)人的見解,如果有錯(cuò)誤的地方误证,希望大家指出继薛!