little 路由相关problem合集

55 阅读1分钟

访问路由不存在则进行重定向

{
    path: '/:pathMatch(.*)',
    redirect: '/welcome',
},

路由命名

页面耦合性高 - 使用动态路由

image.png

触发路由跳转

image.png

获取路由参数信息

image.png

路由守卫 - 是否登录

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/login',
            name: 'login',
            component: () => import('../view/Login.vue'),
        },
        {
            path: "/challenge/:id",
            name:"challenge",
            component: () => import("../view/Challenge1.vue"),
            meta: { requiresAuth:true },
      },
    ]
})
router.beforeEach((to,from,next) =>{ // 一层一层判断好 记得return
    const store = useStore(); //记得要在这个函数里面写,写在函数外面获取不到
    const user = store.state.username;
    if(to === "/login"){
            next()
            return
    }
    if(to.matched.some((record) => record.meta.requiresAuth)){
            if(user){
                    next()
            }else {
                    next("/login")
            }
            return
    }
    next()
})