專案用的 vue+vue-router;
APP返回時自定義的window.back();
全域性快取了window.routerList = [];
前進新增路由,後退刪除路由;
router.js程式碼如下
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const Home = () = >import(/* webpackChunkName: "systemManage" */ './views/Home.vue')
const router = new Router({
routes: [{
path: '/Home',
name: 'Home',
component: Home,
}]
})
window.routerList = [];
router.afterEach((to, from) = >{
window.back = function() {
window.router.isBack = true;
if (window.routerList.length == 0) {
window.router.isBack = false;
return;
} else if (window.routerList.length == 1) {
window.router.isBack = false;
console.log('不能後退了!!!');
} else {
let backPath = window.routerList[window.routerList.length - 2];
window.router.push(backPath);
}
}
if (!window.router.isBack) {
var routerListLen = window.routerList.length;
if (routerListLen > 1 && to.fullPath === window.routerList[routerListLen - 2]) {
window.router.isBack = true;
}
}
// 修改title
document.title = to.meta.title || '預設標題';
if (window.router.isBack) {
console.log('後退') window.routerList.pop();
} else {
console.log('前進') window.routerList.push(to.fullPath);
}
});
window.router = router;
export default router;
複製程式碼
APP.vue也要處理一下window.router.isBack
export default {
watch: {
$route(to, from) {
if (window.router.isBack) {
window.router.isBack = false;
}
}
}
}
複製程式碼
有時候從某個頁面返回到相應頁面,或者當前頁面不記入routerList;
這時候就要做特殊處理了;
方法如下:
// 處理當前頁不記入歷史
const currentRouter = this.$route.fullPath;
// 當前頁路由地址
window.routerList = window.routerList.filter(item => {
return item.indexOf(currentRouter) < 0;
})
// 如果從當前頁跳走又跳回來時有重複路由,則新增下邊這一段程式碼(兩項相等則刪除最後一個)
const rl = window.routerList;
if (window.routerList[rl.length - 1] === rl[rl.length - 2]) {
window.routerList.pop();
}
const targetRoute = '/history/page';
// 清除當前路由以後的所有路由
window.routerList = window.routerList.slice(0, window.routerList.indexOf(targetRoute) + 1)
// 返回到指定路由
let routerList = window.routerList;
const index = routerList.indexOf(targetRoute);
routerList.splice(index + 1, routerList.length - 2);複製程式碼