最近在学习并使用typescript,接触到了很多新类型,今天在学习过程中,看到了RouteRecordRaw这个类型,写篇博客记录一下。
RouteRecordRaw
RouteRecordRaw 是 Vue Router 4 中新增的一个类型定义。
它是用于定义路由记录的。
在 Vue Router 4 中,使用 RouteRecordRaw 来定义路由配置,可以使得路由配置更加清晰和类型安全。(方便typescript进行类型检查!)
RouteRecordRaw 类型定义:
type RouteRecordRaw = {path: string;name?: string;component?: Component;components?: Dictionary<Component>;redirect?: string | Location | NavigationGuard;alias?: string | string[];children?: Array<RouteRecordRaw>;meta?: any;props?: boolean | Object | RoutePropsFunction;caseSensitive?: boolean;pathToRegexpOptions?: PathToRegexpOptions;
}
在 Vue Router 中,path
属性是定义路由的必需属性,它指定了路由的路径。如果没有指定则会导致路由配置不完整或不生效。
这边顺便介绍一下RouteRecordRaw 类型定义中涉及到的其他类型:
1. Component: 表示一个 Vue 组件类型,这个类型来源于 Vue。
2. Dictionary<Component>: 表示一个对象,键是字符串类型,值是组件类型 `Component`。这个类型来源于 TypeScript。
2.5.
Dictionary:Dictionary不是 TypeScript 中的内置类型,而是一种常用的自定义类型约定。在 TypeScript 中,Dictionary
通常用于表示一个键值对对象,其中键是字符串类型,值可以是任意类型。
一个简单的示例:
type Dictionary<T> = {[key: string]: T;
}
Dictionary是一个泛型类型,它接受一个类型参数 T
,表示值的类型。这个类型定义了一个对象,对象的键是字符串类型,值是泛型参数 T
类型。
3. Location: 表示路由的目标位置,可以是一个字符串路径或一个对象,包含路径和其他路由信息。这个类型来源于 Vue Router。
Location的类型定义:
type Location = string | {name?: string;path?: string;hash?: string;query?: Dictionary<string | (string | null)[] | null | undefined>;params?: Dictionary<string>;
}
4. NavigationGuard: 表示一个导航守卫函数,用于路由导航的控制。这个类型来源于 Vue Router。
NavigationGuard的类型定义:
type NavigationGuard = (to: RouteLocationNormalized,from: RouteLocationNormalizedLoaded,next: NavigationGuardCallback
) => any
-
to: RouteLocationNormalized
: 表示导航前的目标路由信息,包括路由的路径、查询参数、哈希、元信息等。 -
from: RouteLocationNormalizedLoaded
: 表示导航前的来源路由信息,包括来源路由的路径、查询参数、哈希、元信息等。 -
next: NavigationGuardCallback
: 表示一个回调函数,用于控制导航的进行。通过调用next
函数,可以实现导航的继续、取消、重定向等操作。
导航守卫函数通常在路由配置中使用,通过注册全局前置守卫、路由独享守卫或组件内的守卫函数来控制路由导航的行为。
注意哦,导航守卫函数的返回值可以是一个 Promise
,用于异步控制导航过程。
5. RoutePropsFunction: 表示一个函数,用于动态生成路由传递给组件的属性。这个类型来源于 Vue Router。
RoutePropsFunction的类型定义:
type RoutePropsFunction = (route: RouteLocationNormalized) => Object
RouteLocationNormalized的类型定义:
interface RouteLocationNormalized {fullPath: string;hash: string;query: RouteQueryAndParameters;params: RouteQueryAndParameters;matched: RouteRecord[];meta: any;name?: string;path: string;redirectedFrom?: string;
}
6. PathToRegexpOptions: 表示路径正则表达式的配置选项,用于指定路径匹配的规则。这个类型来源于 Vue Router。
PathToRegexpOptions的类型定义:
type PathToRegexpOptions = {sensitive?: boolean;strict?: boolean;end?: boolean;start?: boolean;delimiter?: string;endsWith?: string | string[];
}
最近事情比较多,挺久没更新博客了!!恢复学习博客产出!!