导航守卫这里,视频和源码不一致?

来源:11-6 导航守卫

河畔一角

2023-11-14

导航守卫这里,视频里面是调用checkPermission函数,但是源码是调用了loadAsyncRoutes

写回答

1回答

河畔一角

提问者

2023-11-14

导航守卫这里,视频的写法是:

说明:直接通过router.getRoutes()获取所有路由,通过filter进行比对,但是这种方式稍微有点问问题,await loadAsyncRoutes()在本地启动时,可以调用,在打包部署到线上时,有用户反馈报错,因为在外部不支持await方式,所以,需要优化一下调用方式。

await loadAsyncRoutes();
// 判断当前地址是否可以访问
function checkPermission(path) {
    let hasPermission = router.getRoutes().filter(route => route.path == path).length;
    if (hasPermission) {
        return true;
    } else {
        return false;
    }
}
// 导航守卫
router.beforeEach((to, from, next) => {
    if (checkPermission(to.path)) {
        document.title = to.meta.title;
        next()
    } else {
        next('/404')
    }
})

由于不支持await调用,所以课程源码的写法变成了如下方式:

// 修复线上部署不能访问问题
async function loadAsyncRoutes() {
    let userInfo = storage.getItem('userInfo') || {}
    if (userInfo.token) {
        try {
            const { menuList } = await API.getPermissionList()
            let routes = utils.generateRoute(menuList)
            const modules = import.meta.glob('../views/*.vue')
            console.log('views',modules)
            routes.map(route => {
                let url = `../views/${route.name}.vue`
                route.component = modules[url];
                router.addRoute("home", route);
            })
        } catch (error) {
        
        }
    }
}
loadAsyncRoutes();
// 判断当前地址是否可以访问
/*
function checkPermission(path) {
    let hasPermission = router.getRoutes().filter(route => route.path == path).length;
    if (hasPermission) {
        return true;
    } else {
        return false;
    }
}
*/
// 导航守卫
router.beforeEach(async (to, from, next) => {
    if (to.name) {
        if (router.hasRoute(to.name)) {
            document.title = to.meta.title;
            next()
        } else {
            next('/404')
        }
    } else {
        await loadAsyncRoutes()
        let curRoute = router.getRoutes().filter(item => item.path == to.path)
        if (curRoute?.length) {
            document.title = curRoute[0].meta.title;
            next({ ...to, replace: true })
        } else {
            next('/404')
        }
    }
})

先判断路由是否存在,如果存在直接打开,如果不存在,再同步调用菜单接口。

1
0

Vue3+ElementPlus+Koa2 全栈开发后台系统

从前端晋级到全栈,让你的未来发展有更多可能

1069 学习 · 580 问题

查看课程