• 构建vue-router知识体系(三)动态路由基本匹配、简易的 router 实现


    很多时候我们需要将给定匹配模式的路由映射到同一个组件: 例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但是用户的 ID 是不同的; 在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数;

    // 映射表
    {path:'/user/:id',component:()=>import('../pages/User.vue')
    } 
    
    • 1
    • 2
    • 3

    router-link 跳转

     
    
    • 1

    获取动态路由的值

    User 中如何获取到对应的值呢 在 template 中,直接通过 $route.params 获取值;

    • 在 created 中,通过 this.$route.params 获取值;
    • 在 setup 中,我们要使用 vue-router 库给我们提供的一个 hook useRoute;* 该 Hook 会返回一个 Route 对象,对象中保存着当前路由相关的值;
     
    
    • 1
    • 2
    export default {
    created() {console.log(this.$route.params.id)
    },
    setup() {const route = useRoute()console.log(route)console.log(route.params.id)
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5

    匹配多个参数

    // 映射表
    {path:'/user/:id/:info',component:()=>import('../pages/User.vue')
    }
    
    this.$route.params => {id:'xxx',info:'yyy'} 
    
    • 1
    • 2
    • 3
    • 4
    • 5

    NotFound

    对于哪些没有匹配到的路由,我们通常会匹配到固定的某个页面 比如 NotFound 的错误页面中,这个时候我们可编写一个动态路由用于匹配所有的页面;

    // 映射表
    {path:'/:pathMatch(.*)',component:()=>import('../pages/User.vue')
    } 
    
    • 1
    • 2
    • 3

    获取到传入的参数

    $route.params.pathMatch

    匹配规则加*

    Not Found: [ "user", "hahah", "123"] => path:'/:pathMatch(.*)*",
    Not Found: user/hahah/123 => path:'/:pathMatch(.*)", 
    
    • 1
    • 2

    路由的嵌套

    目前我们匹配的 Home、About、User 等都属于底层路由,我们在它们之间可以来回进行切换; 但是呢,我们 Home 页面本身,也可能会在多个组件之间来回切换:

    • 比如 Home 中包括 Product、Message,它们可以在 Home 内部来回切换;

    这个时候我们就需要使用嵌套路由,在 Home 中也使用 router-view 来占位之后需要渲染的组件;

    路由的嵌套配置

    {
    path: '/home',
    component:()=> import(/* webpackChunkName:"home-chunk "*/"./pages/Home.vue"),
    children:[{path:redirect: "/home/product'},{path:'product',component: ()=> import('../pages/HomeProduct.vue")},{ path:'message', component: ()=>import('../pages/HomeMessage.vue")}
    ],
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    代码的页面跳转

    使用 push 的特点是压入一个新的页面,那么在用户点击返回时,上一个页面还可以回退,但是如果我们希望当前 页面是一个替换操作,那么可以使用 replace

    
     
    
    • 1
    • 2

    vue2

    jumpToProfile(){// 直接传入值this.$router.push('/profile')// 传入一个对象this.$router.push({path:'/profile'})
    } 
    
    • 1
    • 2

    vue3

    const router = useRouter()
    const jumpToProfile = router.replace('/profile") 
    
    • 1
    • 2

    query 方式的参数

    jumpToProfile() {this.$router.push(path: "/profile",query:{ name:"why", age: 18 }})
    } 
    
    • 1
    • 2

    在界面中通过 $route.query 来获取参数:

    query: {{ $route.query.name }}-{{ $route.query.age }}

    • 1

    页面的前进后退

    go
    // 向前移动一条记录,与 router.forward() 相同
    router.go(1)
    // 返回一条记录,与router.back()• 相同
    router.go(-1)
    // 前进3 条记录
    router.go(3)
    // 如果没有那么多记录,静默失败
    router.go(-100)
    router.go(100) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    back:

    通过调用 history.back() 回溯历史。相当于 router.go(-1);

    forward:

    通过调用 history.forward() 在历史中前进。相当于 router.go(1);

    router-link 的 v-slot

    在 vue-router3.x 的时候,router-link 有一个 tag 属性,可以决定 router-link 到底渲染成什么元素: 但是在 vue-router4.x 开始,该属性被移除了;

    • 而给我们提供了更加具有灵活性的 v-slot 的方式来定制渲染的内容;* v-slot 如何使用呢?* 首先,我们需要使用 custom 表示我们整个元素要自定义
    • 如果不写,那么自定义的内容会被包裹在一个 a 元素中;* 其次,我们使用 v-slot 来作用域插槽来获取内部传给我们的值:
    • href:解析后的 URL;
    • route:解析后的规范化的 route 对象;
    • navigate:触发导航的函数;
    • isActive:是否匹配的状态;
    • isExactActive:是否是精准匹配的状态;
    
    <- @click="navigate">跳转about

    href: {{ href }}

    route: {{ route }}

    isActive: {{ isActive}}

    isExactActive: {{ isExactActive }}

    • 1
    • 2
    • 3
    • 4
    • 5

    router-view 的 v-slot

    router-view 也提供给我们一个插槽,可以用于 组件来包裹你的路由组件:

    • Component:要渲染的组件;
    • route:解析出的标准化路由对象;

    动态路由处理

    动态添加

    某些情况下我们可能需要动态的来添加路由:

    • 比如根据用户不同的权限,注册不同的路由;
    • 这个时候我们可以使用一个方法 addRoute;

    如果我们是为 route 添加一个 children 路由,那么可以传入对应的 name: 动态添加一个路由

    const categoryRoute = { path:'/category', component: () => import ('../pages/Category.vue')
    }
    router.addRoute(categoryRoute) 
    
    • 1
    • 2
    • 3
    const categoryRoute = { path:'/home', component: () => import ('../pages/Category.vue')
    }
    router.addRoute('home', homeMomentRoute) 
    
    • 1
    • 2
    • 3

    动态删除路由

    方式一:添加一个 name 相同的路由;

    router.addRoute({ path: '/about' name: "about",component: About}
    // 这将会删除之前己经添加的路由,因为他们具有相同的名字且各字必须是唯一的
    router.addRoute({ path: '/other' name: "about",component: About} 
    
    • 1
    • 2
    • 3

    方式二:通过 removeRoute 方法,传入路由的名称;

    router.addRoute({ path: '/about' name: "about",component: About})
    // 删除路由如果存在的话
    router.removeRoute('about') 
    
    • 1
    • 2
    • 3

    方式三:通过 addRoute 方法的返回值回调

    const removeRoute = router.addRoute({ path: '/about' name: "about",component: About}
    removeRoute() 
    
    • 1
    • 2

    检查路由是否存在

    • router.hasRoute():检查路由是否存在。
    • router.getRoutes():获取一个包含所有路由记录的数组。

    简易 mini-router

    let Vue;
    
    class VueRouter {constructor(options) {this.$options = options;this.routerMap = {};this.app = new Vue({data: {current: "/",},});}init() {this.bindEvent();// 初始化组件this.initComponent();// 做一个路由的映射关系表this.createRouteMap(this.$options);}bindEventListener(type) {const historyEvent = history[type];return function () {const newEvent = historyEvent.apply(this, arguments);const e = new Event(type);e.arguments = arguments;window.dispatchEvent(e);return newEvent;};}// 监听bindEvent() {// 刚刚进入页面的,页面改变了吗?没有的window.addEventListener("load", this.onHashChange.bind(this), false);window.addEventListener("hashchange", this.onHashChange.bind(this), false);history.pushState = this.bindEventListener("pushState");window.addEventListener("pushState", this.onHashChange.bind(this), false);}// 改变后的方法onHashChange() {console.log("当前的路由");this.app.current = window.location.hash.slice(1) || "/";}// 初始化组件initComponent() {// link我们需要他是一个链接Vue.component("router-link", {props: {to: String,},render(h) {// return {this.$slots.default};return h("a",{attrs: {href: "#" + this.to,},},[this.$slots.default]);},});Vue.component("router-view", {render: (h) => {let component = this.routerMap[this.app.current].component;return h(component);},});}createRouteMap(options) {options.routes.forEach((item) => {this.routerMap[item.path] = item;});console.log(this.routerMap);}
    }
    
    VueRouter.install = function (_Vue) {Vue = _Vue;Vue.mixin({beforeCreate() {if (this.$options.router) {Vue.prototype.$router = this.$options.router;// 确保只执行一次,并且初始化一次this.$options.router.init();}},});
    };
    
    export default VueRouter; 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 相关阅读:
    流量传感器原理介绍
    YOLOv8+swin_transfomerv2
    【CSS】5分钟带你彻底搞懂 W3C & IE 盒模型
    【Spring框架】Spring概述及基本应用
    二叉树MFC实现
    软考程序员考试大纲(2023)
    Tomcat总体架构,启动流程与处理请求流程
    IDEA和Tomcat服务器的整合
    Windows VS C++工程:包含目录、库目录、附加依赖项、附加包含目录、附加库目录配置与静态库、动态库的调用——以OCCI的配置为例
    模拟一个火车站售票小例子
  • 原文地址:https://blog.csdn.net/web220507/article/details/126583978