vue3 使用 vue-router

发布时间 2023-10-03 21:48:35作者: 灵火

安装 vue-router

pnpm i vue-router

使用 vue-router

创建自己的 router

// @/route/index.ts
import {createRouter, createWebHashHistory} from 'vue-router'
import type {RouteRecordRaw} from "vue-router"

const routes: RouteRecordRaw[] = [
    {
        path: '/',
        redirect: "/dashboard/console",
        meta: {
            hidden: true,
            title: "首页面板"
        },
    },
    {
        path: '/demo',
        component: () => import('@/view/demo/demo.vue'),
        meta: {
            hidden: true,
            title: "demo 页面"
        },
    },
    {
        path: '/login',
        component: () => import('@/view/account/login.vue'),
        meta: {
            hidden: true,
            title: '登录'
        },
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

添加拦截器

// @/route/index.ts

// 需要安装 nprogress `pnpm i nprogress`
// import NProgress from "nprogress";
// import "nprogress/nprogress.css";
import type { NavigationGuardNext, RouteLocationNormalized} from "vue-router";

const parseJSON =  (source: string | object | null) => {
  if(!source) return source;
  if(source instanceof Object) return JSON.parse(JSON.stringify(source));
  if(typeof source === 'string') return JSON.parse(source);
}

router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    // 添加进度条
    // NProgress.start();
    const {meta} = to
    // 设置标题
    document.title = `back-end-${meta.title}`
    // 使用 pinia 创建的 store,state 里保存的登录的 JWT token 和 用户可以访问的 menu
    const userStore = useUserStore()
    const token = userStore.token;       // JWT token
    const menu = userStore.menu; // menu list
    const userMenuList: Array<RouteRecordRaw> = parseJSON(menu)

    if (!to.fullPath.includes('login') && !token) {
        next({path: '/login'})
    }

    if (userMenuList.filter(route => route.path === to.path).length !== 0) {
        next()
    }

    next("/demo")
})

router.afterEach((_, _, _) => {
    // 添加进度条
    // NProgress.done();
})

在 main.ts 里挂载 vue-router

import {createApp} from 'vue'
import App from './App.vue'
import router from "@/route/index.ts"

const app = createApp(App);
app.use(router);
app.mount("#app");