Vue3 如何使用 vue-router 以及路由权限拦截

时间:2025-02-18 08:53:39
// 1. 引入这两个函数来初始化路由 import { createRouter, createWebHashHistory } from "vue-router" // 2. 配置路由 const routes = [ { path: '/info', name: 'info', component: () => import('@/pages/info'), // 路由元信息,随你怎么定义,笔者一般采用这种方式来定义路由权限然后结合路由拦截, // 下面的 auth:true 表示需要授权登录才可以进入此页面。 meta: { auth: true, }, }, { path: '/login', name: 'login', component: () => import('@/pages/login'), meta: { auth: false, }, } ] // 3. 创建路由实例 const router = createRouter({ history: createWebHashHistory(), // 表示使用 hash 模式,即 url 会有 # 前缀 routes }) // 4. 你还可以监听路由拦截,比如权限验证。 router.beforeEach((to, from, next) => { // 1. 每个条件执行后都要跟上 next() 或 使用路由跳转 api 否则页面就会停留一动不动 // 2. 要合理的搭配条件语句,避免出现路由死循环。 const token = cookies.get('token') if (to.meta.auth) { if (!token) { return router.replace({ name: 'login' }) } next() } else { next() } }) export default router