vueRouter4.0+ts

短命女 2022-10-16 06:04 349阅读 0赞

准备工作

需要了解的接口

官方提供的路由对象数据类型

RouteRecordRaw

自定义定义路由对象数据类型

  1. // Omit 删除指定类型的key返回删除后的接口类型
  2. export interface AppRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'> {
  3. name: string;
  4. meta: RouteMeta;
  5. component?: Component | string;
  6. components?: Component;//一个页面或者视图多个路由会使用
  7. children?: AppRouteRecordRaw[];
  8. props?: any;
  9. fullPath?: string;
  10. }

路由目录结构

在这里插入图片描述
type 路由对象类型

type.ts

  1. export interface RouteMeta {
  2. title: string;
  3. }
  4. export interface AppRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'> {
  5. name: string;
  6. meta: RouteMeta;
  7. component?: Component | string;
  8. components?: Component;//一个页面或者视图多个路由会使用
  9. children?: AppRouteRecordRaw[];
  10. props?: any;
  11. fullPath?: string;
  12. }
  13. export type AppRouteModule = AppRouteRecordRaw;

routes/index.ts

  1. import { RouteRecordRaw } from 'vue-router';
  2. // import.meta.globEager 是vite提供的函数可以引入指定目录里面的所有指定类型文件返回数组
  3. const modules = import.meta.globEager('./modules/**/*.ts');
  4. const routeModuleList: RouteRecordRaw[] = [];
  5. Object.keys(modules).forEach((key) => {
  6. const mod = modules[key].default || { };
  7. // console.log('mod :>> ', mod);
  8. const modList = Array.isArray(mod) ? [...mod] : [mod];
  9. routeModuleList.push(...modList);
  10. });
  11. // 处理好数据后统一返回到 路由实例
  12. export const basicRoutes:RouteRecordRaw[] =routeModuleList;

创建路由module

  1. import { AppRouteModule } from "../../types";
  2. const LoginRoute: AppRouteModule = {
  3. path: '/login',
  4. name: 'Login',
  5. component: () => import('/@/views/sys/login/Login.vue'),
  6. meta: {
  7. title: "登录",
  8. },
  9. };
  10. export default LoginRoute;

创建路由实例

  1. import type { App } from 'vue';
  2. import type { RouteRecordRaw } from 'vue-router';
  3. import { createRouter, createWebHashHistory } from 'vue-router';
  4. import { basicRoutes } from './routes';
  5. /** * 创建路由实例 */
  6. export const router = createRouter({
  7. history:createWebHashHistory(),
  8. routes:(basicRoutes as unknown) as RouteRecordRaw[]
  9. });
  10. /** * 路由拦截 */
  11. router.beforeEach((to,from)=>{
  12. console.log('to :>> ', to,from);
  13. })
  14. /** * 挂载到vue实例函数 * @param app vue实例 */
  15. export function setupRouter(app: App<Element>) {
  16. app.use(router);
  17. }
  18. export default router;

发表评论

表情:
评论列表 (有 0 条评论,349人围观)

还没有评论,来说两句吧...

相关阅读

    相关 VueRouter路由嵌套

    1. 前言 本小节我们介绍如何嵌套使用 VueRouter。嵌套路由在日常的开发中非常常见,如何定义和使用嵌套路由是本节的重点。同学们在学完本节课程之后需要自己多尝试配置

    相关 VueRouter路由传参

    1. 前言 本小节我们介绍 VueRouter 路由组件传参。包括 params 传参、query 传参的两种方式。路由传参的知识点非常重要,在日常开发中,我们经常会通过

    相关 vueRouter4.0+ts

    准备工作 需要了解的接口 官方提供的路由对象数据类型 > RouteRecordRaw 自定义定义路由对象数据类型 // Omit 删除指定类型的ke