vue-router核心TS类型

news2024/9/24 13:25:23

 NavigationFailureType 枚举:

export declare enum NavigationFailureType {
    /**
     * An aborted navigation is a navigation that failed because a navigation
     * guard returned `false` or called `next(false)`
     */
    aborted = 4,
    /**
     * A cancelled navigation is a navigation that failed because a more recent
     * navigation finished started (not necessarily finished).
     */
    cancelled = 8,
    /**
     * A duplicated navigation is a navigation that failed because it was
     * initiated while already being at the exact same location.
     */
    duplicated = 16
}
三种状态:

        aborted:程序终端,导航守卫return false,或调用next(false)

        cancelled: 快速切换到其他路由

        duplicated: 切换到当前的路由

 HistoryState:

export declare interface HistoryState {
    [x: number]: HistoryStateValue;
    [x: string]: HistoryStateValue;
}

该类型定义可以优化为:

export declare interface HistoryState {
    [x: number | string]: HistoryStateValue
}

HistoryState 类型主要用于描述浏览器历史记录中的状态对象。当用户通过浏览器的前进/后退按钮或者通过其他方式(如程序逻辑触发的导航)在不同的路由之间导航时,Vue Router 会利用浏览器的history的 API (history.pushState, history.replaceState) 来管理这些导航。

应用:

执行一个导航时,可以通过 pushState 或 replaceState 方法传递一个 HistoryState 对象来保存一些额外的信息

beforeRouteEnter 和 beforeRouteUpdate 导航守卫来访问这些状态对象

NavigationGuardNext:

export declare interface NavigationGuardNext {
    (): void;
    (error: Error): void;
    (location: RouteLocationRaw): void;
    (valid: boolean | undefined): void;
    (cb: NavigationGuardNextCallback): void;
}

next函数的类型定义,这里使用了类型重载

next可以什么都不传;可以传入Error对象;可以传入路由地址,可以传入布尔值,也可以传入一个回调函数,传入回调函数的场景很少用到。

经常使用的是next(),next(false)和next(path)

declare type NavigationGuardNextCallback = (vm: ComponentPublicInstance) => unknown;

NavigationGuardNextCallback函数的入参是vue组件实例对象。

RouteLocationOptions:

export declare interface RouteLocationOptions {
    /**
     * Replace the entry in the history instead of pushing a new entry
     */
    replace?: boolean;
    /**
     * Triggers the navigation even if the location is the same as the current one.
     * Note this will also add a new entry to the history unless `replace: true`
     * is passed.
     */
    force?: boolean;
    /**
     * State to save using the History API. This cannot contain any reactive
     * values and some primitives like Symbols are forbidden. More info at
     * https://developer.mozilla.org/en-US/docs/Web/API/History/state
     */
    state?: HistoryState;
}

当使用 router.push() 或 router.replace() 时传入的对象属性,这里只包含了部分。这里定义了强制刷新,history里是否替换,以及传入state

RouterOptions: 路由实例化的配置选项

export declare interface RouterOptions extends PathParserOptions {
    /**
     * History implementation used by the router. Most web applications should use
     * `createWebHistory` but it requires the server to be properly configured.
     * You can also use a _hash_ based history with `createWebHashHistory` that
     * does not require any configuration on the server but isn't handled at all
     * by search engines and does poorly on SEO.
     *
     * @example
     * ```js
     * createRouter({
     *   history: createWebHistory(),
     *   // other options...
     * })
     * ```
     */
    history: RouterHistory;
    /**
     * Initial list of routes that should be added to the router.
     */
    routes: Readonly<RouteRecordRaw[]>;
    /**
     * Function to control scrolling when navigating between pages. Can return a
     * Promise to delay scrolling. Check {@link ScrollBehavior}.
     *
     * @example
     * ```js
     * function scrollBehavior(to, from, savedPosition) {
     *   // `to` and `from` are both route locations
     *   // `savedPosition` can be null if there isn't one
     * }
     * ```
     */
    scrollBehavior?: RouterScrollBehavior;
    /**
     * Custom implementation to parse a query. See its counterpart,
     * {@link RouterOptions.stringifyQuery}.
     *
     * @example
     * Let's say you want to use the [qs package](https://github.com/ljharb/qs)
     * to parse queries, you can provide both `parseQuery` and `stringifyQuery`:
     * ```js
     * import qs from 'qs'
     *
     * createRouter({
     *   // other options...
     *   parseQuery: qs.parse,
     *   stringifyQuery: qs.stringify,
     * })
     * ```
     */
    parseQuery?: typeof parseQuery;
    /**
     * Custom implementation to stringify a query object. Should not prepend a leading `?`.
     * {@link RouterOptions.parseQuery | parseQuery} counterpart to handle query parsing.
     */
    stringifyQuery?: typeof stringifyQuery;
    /**
     * Default class applied to active {@link RouterLink}. If none is provided,
     * `router-link-active` will be applied.
     */
    linkActiveClass?: string;
    /**
     * Default class applied to exact active {@link RouterLink}. If none is provided,
     * `router-link-exact-active` will be applied.
     */
    linkExactActiveClass?: string;
}

createRouter()函数传入的配置对象

Router类型:

        Router类型是Vue-Router的实例类型,createRouter()函数的返回值类型

        它拥有currentRoute和options属性,都是只读的

        listening属性是可读写的

        另外,还有方法,go 、forward 、 back、addRoute  deleteRoute  replace hasRoute getRoutes  resolve  push replace beforeEach beforeResove afterEach onError  isReady install

        通过useRouter()函数可以获取router,因此,可以获取当前的路由

RouteLocation:

        就是Route实例对象的类型的基类型。该类型继承自_RouteLocationBase类型,_RouteLocationBase类型又继承自MatcherLocation的部分属性:

export declare interface _RouteLocationBase extends Pick<MatcherLocation, 'name' | 'path' | 'params' | 'meta'> {
    /**
     * The whole location including the `search` and `hash`. This string is
     * percentage encoded.
     */
    fullPath: string;
    /**
     * Object representation of the `search` property of the current location.
     */
    query: LocationQuery;
    /**
     * Hash of the current location. If present, starts with a `#`.
     */
    hash: string;
    /**
     * Contains the location we were initially trying to access before ending up
     * on the current location.
     */
    redirectedFrom: RouteLocation | undefined;
}

Pick<MatcherLocation, 'name' | 'path' | 'params' | 'meta'>

因此,该实例类型的属性有:

        name  path  params   meta   fullPath  query  hash  redirectedFrom  如图所示:

其中,matched属性是RouteLocation类型自带的:

export declare interface RouteLocation extends _RouteLocationBase {
    /**
     * Array of {@link RouteRecord} containing components as they were
     * passed when adding records. It can also contain redirect records. This
     * can't be used directly
     */
    matched: RouteRecord[];
}

RouteRecord:

        该类型是RouteRecordNormalized的类型别名,该类型的作用就是我们配置给路由实例Router配置的路由表:

export declare type RouteRecord = RouteRecordNormalized;
export declare interface RouteRecordNormalized {
    /**
     * {@inheritDoc _RouteRecordBase.path}
     */
    path: _RouteRecordBase['path'];
    /**
     * {@inheritDoc _RouteRecordBase.redirect}
     */
    redirect: _RouteRecordBase['redirect'] | undefined;
    /**
     * {@inheritDoc _RouteRecordBase.name}
     */
    name: _RouteRecordBase['name'];
    /**
     * {@inheritDoc RouteRecordMultipleViews.components}
     */
    components: RouteRecordMultipleViews['components'] | null | undefined;
    /**
     * Nested route records.
     */
    children: RouteRecordRaw[];
    /**
     * {@inheritDoc _RouteRecordBase.meta}
     */
    meta: Exclude<_RouteRecordBase['meta'], void>;
    /**
     * {@inheritDoc RouteRecordMultipleViews.props}
     */
    props: Record<string, _RouteRecordProps>;
    /**
     * Registered beforeEnter guards
     */
    beforeEnter: _RouteRecordBase['beforeEnter'];
    /**
     * Registered leave guards
     *
     * @internal
     */
    leaveGuards: Set<NavigationGuard>;
    /**
     * Registered update guards
     *
     * @internal
     */
    updateGuards: Set<NavigationGuard>;
    /**
     * Registered beforeRouteEnter callbacks passed to `next` or returned in guards
     *
     * @internal
     */
    enterCallbacks: Record<string, NavigationGuardNextCallback[]>;
    /**
     * Mounted route component instances
     * Having the instances on the record mean beforeRouteUpdate and
     * beforeRouteLeave guards can only be invoked with the latest mounted app
     * instance if there are multiple application instances rendering the same
     * view, basically duplicating the content on the page, which shouldn't happen
     * in practice. It will work if multiple apps are rendering different named
     * views.
     */
    instances: Record<string, ComponentPublicInstance | undefined | null>;
    /**
     * Defines if this record is the alias of another one. This property is
     * `undefined` if the record is the original one.
     */
    aliasOf: RouteRecordNormalized | undefined;
}

这里有几个比较陌生的属性:props,beforeEnter,leaveGuards, updateGuards,enterCallbacks,instances,aliasOf

需要注意的是这些属性的值的类型

NavigationGuard:

        定义的是导航的路由守卫

        

/**
 * Navigation guard. See [Navigation
 * Guards](/guide/advanced/navigation-guards.md).
 */
export declare interface NavigationGuard {
    (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): NavigationGuardReturn | Promise<NavigationGuardReturn>;
}

RouterView:

/**
 * Component to display the current route the user is at.
 */
export declare const RouterView: new () => {
    $props: AllowedComponentProps & ComponentCustomProps & VNodeProps & RouterViewProps;
    $slots: {
        default?: (({ Component, route, }: {
            Component: VNode;
            route: RouteLocationNormalizedLoaded;
        }) => VNode[]) | undefined;
    };
};

RouterView是一个类构造函数,参数是空,并返回一个具有特定属性的对象。

$props 属性定义了 RouterView 组件可以接受的 prop 类型。

$slots: {: 定义了 RouterView 组件的插槽(slot)结构。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1971569.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

arduino程序-MC猜数字5、6(基础知识)

arduino程序-MC猜数字5、6&#xff08;基础知识&#xff09; 1-23 MC猜数字-5 自定义函数自定义函数自定义清理显示内容函数displayClear&#xff08;&#xff09;带参数函数displayNumber带参数、返回值的函数 1-24 MC猜数字-6 完成制作显示0~9数字函数改造产生随机数字函数改…

嵌入式人工智能(42-基于树莓派4B的红外遥控)

1、简介 红外遥控想必对大家来说都不陌生&#xff0c;红外也属于无线通信的一种&#xff0c;只要是无线通信&#xff0c;必然要用电磁波&#xff0c;要理解无线通信的本质和原理&#xff0c;不管用哪个频段都要学习电磁场与电磁波&#xff0c;这是一个难度很大的课&#xff0c…

IT事件经理在数字企业中的角色和责任

什么是IT事件经理&#xff1f; IT事件经理有时也被称为事件指挥官&#xff0c;他们承担着管理组织事件响应的总体责任&#xff0c;从委派各种事件响应任务到与每个利益相关者进行沟通和协调。 示例&#xff1a;当一个全球性的电子商务平台在一次销售活动中流量激增&#xff0c…

George Danezis谈Mysticeti的共识性能

Sui的新共识引擎Mysticeti已经在主网上开始分阶段推出。Mysten Labs联合创始人兼首席科学家George Danezis在采访中&#xff0c;讨论了其低延迟如何通过高性能应用程序提升用户体验。 采访视频&#xff1a; https://youtu.be/WHvtPQUa2Q0 中文译文&#xff1a;延迟和吞吐量对…

LSTM与GNN强强结合!全新架构带来10倍推理速度提升

今天来推荐一个深度学习领域很有创新性的研究方向&#xff1a;LSTM结合GNN。 GNN擅长处理图数据关系和特征&#xff0c;而LSTM擅长处理时间序列数据及长期依赖关系。通过将两者结合&#xff0c;我们可以有效提升时间序列预测的准确性和效率&#xff0c;尤其是在处理空间和时间…

手搓交换排序、归并排序、计数排序

文章目录 交换排序冒泡排序快速排序hoare版本挖坑法lomuto前后指针 非递归快速排序 归并排序实现计数实现排序代码测试排序算法性能 交换排序 冒泡排序 void BubbleSort(int* arr, int n) {for (int i 0; i < n; i){int flag 0;for (int j 0; j < n - i - 1; j){if …

day13 Java基础——逻辑运算符,位运算符及面试题

day13 Java基础——逻辑运算符&#xff0c;位运算符及面试题 1. 逻辑运算符&#xff1a;与&#xff0c;或&#xff0c;非 package operator;public class Demo07 {public static void main(String[] args) {boolean a true;boolean b false;System.out.println("a &…

【网络问题】网络诊断:远程计算机或设备将不接受连接的解决办法/DNS服务器可能不可用

当网络出现问题时&#xff0c;一定要点击“请尝试运行Windows网络诊断”来获取具体的网络问题&#xff0c; 今天碰到且得以解决的两个问题&#xff1a; 一、远程计算机或设备将不接受连接的解决办法 打开控制面板——点击“网络和Internet”——点击“Internet选项”&#xf…

电脑自动重启是什么原因?重启原因排查和解决办法!

当你的电脑突然毫无预警地自动重启&#xff0c;不仅打断了工作流程&#xff0c;还可能导致未保存的数据丢失&#xff0c;这无疑令人很懊恼&#xff0c;那么&#xff0c;电脑自动重启是什么原因呢&#xff1f;有什么方法可以解决呢&#xff1f;别担心&#xff0c;在大多数情况下…

《从零开始:使用Python构建简单Web爬虫》

前言 随着互联网信息的爆炸性增长&#xff0c;如何高效地获取和处理这些数据变得越来越重要。Web爬虫作为一种自动化工具&#xff0c;可以帮助我们快速抓取所需的网页内容。本文将介绍如何使用Python编写一个简单的Web爬虫&#xff0c;并通过实例演示其基本用法。 准备工作 …

创建互动照片墙:HTML、CSS 和 JavaScript 实战

在这个数字化时代&#xff0c;照片已经成为我们生活中不可或缺的一部分。无论是记录重要时刻&#xff0c;还是分享日常生活&#xff0c;我们都离不开照片。今天&#xff0c;我们将一起探索如何使用 HTML、CSS 和 JavaScript 创建一个互动的照片墙程序&#xff0c;让您可以轻松展…

四步构建App跨渠道归因分析方法

通常来讲&#xff0c;在互联网场景中&#xff0c;最简单也最常用的App归因模型就是基于最后一次点击来源进行归因转化&#xff0c;因为越靠近决策环节的时刻通常影响就越大。 不过有机构对营销测量的研究发现&#xff0c;只有11%的营销人员对他们的归因模型的准确性感到“非常…

大语言模型(LLM)快速理解

自2022年&#xff0c;ChatGPT发布之后&#xff0c;大语言模型&#xff08;Large Language Model&#xff09;&#xff0c;简称LLM掀起了一波狂潮。作为学习理解LLM的开始&#xff0c;先来整体理解一下大语言模型。 一、发展历史 大语言模型的发展历史可以追溯到早期的语言模型…

视频孪生:如何有效利用智慧机房里的视频监控系统?

机房是存储设备和数据的重要场所。常见的机房安全隐患有电源不稳定、设备温度异常、空调及新风系统故障、机房漏水等&#xff0c;因此需要管理人员全天轮班值守巡检。传统机房运维工作繁琐且效率低下&#xff0c;对监控设备的利用率不高&#xff0c;而视频孪生技术能很好地解决…

02 pip指令的使用

pip 是一个现代的&#xff0c;通用的 Python 包管理工具 。提供了对Python 包的查找、下载、安装、卸载的功能。 1. 在安装好的python环境下&#xff0c;进入以下目录可以查看到pip命令。 同样在windows命令窗口进行测试&#xff0c;pip命令是否可用。WindowsR键&#xff0c;使…

“职场中,不要和上司作对”,真的很重要吗?你认同这句话吗?

在职场上&#xff0c;领导对下属的期望永远都只有两个字&#xff0c;不是忠诚&#xff0c;也不是能力&#xff0c;而是省心。 领导对下属的要求就是别让我操心。 在职场中&#xff0c;通常面临的首要问题就是如何与领导相处。 把职场中的前辈当作老师来尊重&#xff0c;你尊…

基础复习(多线程)

线程创建方式 1.继承Thread类 2.实现Runable接口 3.Callable接口实现有返回值的线程 &#xff08;1&#xff09;第一种 提供了一个类叫做Thread&#xff0c;此类的对象用来表示线程。创建线程并执行线程的步骤如下 1.定义一个子类继承Thread类&#xff0c;并重写run方法 2.创建…

无密码sudo

文件路径&#xff1a;/etc/sudoers 修改sudoers文件 进去root 权限&#xff1a;sudo su 加入sudoers 写权限&#xff1a;chmod w sudoers 修改sudoers文件&#xff1a;vim sudoers 根据下面图片修改 wq退出编辑

华为LTC流程体系详解

LTC&#xff0c;全称Lead to Cash&#xff0c;中文翻译为从线索到现金&#xff0c;是一种企业运营管理思想&#xff0c;也是一个集成的业务流程。它涵盖了企业从接触客户到收到客户回款的整个流程&#xff0c;通过科学化管理&#xff0c;实现更高效地将线索客户转化为付费客户。…

学习web前端三大件之HTML篇

HTML的全称为超文本标记语言&#xff0c;是一种标记语言。它包括一系列标签&#xff0c;通过这些标签可以将网络上的文档格式统一&#xff0c;使分散的Internet资源连接为一个逻辑整体。HTML文本是由HTML命令组成的描述性文本&#xff0c;HTML命令可以说明文字&#xff0c;图形…