项目用的 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);复制代码


转载于:https://juejin.im/post/5c0e128e51882569732423de

Logo

前往低代码交流专区

更多推荐