九 · 从零开始搭建一个项目(添加路由守卫)

46 阅读1分钟

1.router目录 -> index.ts 改造

项目下载链接
https://shattered-dream.oss-cn-beijing.aliyuncs.com/web/app-web.zip
因为需要添加守卫所以需要路由的实例 给他赋个值就可以了 然后去写 beforeEach(注: next()必须得调用否则路由无法跳转)
const router = createRouter({
    history: createWebHistory(),
    routes,
});


router.beforeEach((to, from, next) => {
    console.log(to)
    console.log(from)

    next();
});



export default router;

image.png

2.获取当前登陆的用户 如果用户登陆了直接让他去首页,如果没有登陆那么就去登陆或者注册

然后启动项目就发现成功实现了未登录无法去到除了登录页和注册页以外的所有页面了
router.beforeEach((to, _, next) => {
    const currentUser = 'current_user'  //避免写错
    const {getLocalStore} = useLocalStore()
    // 如果当前在登陆页面或者注册页面
    if (to.path === '/login' || to.path === '/register') {
        // 那么判断是否登陆过
        if (getLocalStore(currentUser)) {
            // 登陆过直接去首页
            next('/');
        } else {
            next();
        }
        // 如果当前不是登陆注册页面
    } else {
        // 判断是否登陆过
        if (!getLocalStore(currentUser)) {
            // 没有登陆过
            next('/login');
        } else {
            next();
        }
    }
});

image.png