Vue Router深入学习(一)

简介: Vue Router深入学习(一)

Vue Router深入学习(一)

之前的笔记:Vue路由

通过阅读文档,自己写一些demo来加深自己的理解。(主要针对Vue3)

1. 动态路由匹配

1.1 捕获所有路由(404路由)

const routes = [
// 将匹配所有内容并将其放在 `$route.params.pathMatch` 下
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
// 将匹配以 `/user-` 开头的所有内容,并将其放在 `$route.params.afterUser` 下
{ path: '/user-:afterUser(.*)', component: UserGeneric },
]

使用

import { createRouter, createWebHashHistory } from "vue-router"


const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: "/home",
    name: "Home",
    component: () => import("../components/Home.vue")
  },
  {
    path: '/user-:afterUser(.*)',
    // 将匹配以 `/user-` 开头的所有内容,并将其放在 `$route.params.afterUser` 下
    name: 'User',
    component: () => import('../components/User.vue')
  },
  {
    path: "/:pathMatch(.*)*",
    // 将匹配所有内容并将其放在 `$route.params.pathMatch` 下
    name: 'NotFound',
    component: () => import("../components/NotFound.vue")
  }
]

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

export default router

app.vue

<template>
  {{ route.params }}
  <router-view></router-view>
</template>


<script setup>
import { useRoute } from 'vue-router'

const route = useRoute()

</script>

image-20220302183444782

2 路由的匹配语法

主要是通过正则表达式的语法来实现

2.1 在参数中自定义正则

语法:

const routes = [
// /:orderId -> 仅匹配数字
{ path: '/:orderId(\\d+)' },
// /:productName -> 匹配其他任何内容
{ path: '/:productName' },
]

实践:

路由配置:

import { createRouter, createWebHashHistory, useRoute } from "vue-router"


const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: "/home",
    name: "Home",
    component: () => import("../components/Home.vue")
  },
  {
    path: "/user/:userid(\\d+)",   // 两个\是因为会被转义
    name: "UserId",
    component: () => import('../components/UserId.vue')
  },
  {
    path: '/user/:username',
    name: "UserName",
    component: () => import('../components/UserName.vue')
  }
]

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

export default router

vue-router

2.2 可重复的参数

可以使用 *(0个或多个)和 +(1个或多个)将参数标记为可重复

语法:

const routes = [
// /:chapters ->  匹配 /one, /one/two, /one/two/three, 等
{ path: '/:chapters+' },
// /:chapters -> 匹配 /, /one, /one/two, /one/two/three, 等
{ path: '/:chapters*' },
]

实践:

*

import { createRouter, createWebHashHistory, useRoute } from "vue-router"


const routes = [
  {
    path: "/:chapters*",
    name: "Chapters",
    component: () => import("../components/Chapters.vue")
  }
]

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

export default router

vue-router

+

vue-router

2.3 可选参数

使用 ? 修饰符(0 个或 1 个)将一个参数标记为可选

语法:

const routes = [
// 匹配 /users 和 /users/posva
{ path: '/users/:userId?' },
// 匹配 /users 和 /users/42
{ path: '/users/:userId(\\d+)?' },
]

实践:

const routes = [
  {
    path: '/user/:userid(\\d+)?',
    name: 'User',
    component: () => import('../components/User.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../components/NotFound.vue')
  },
]

image-20220303103934235

如果没加可选限制,那么访问/user时也会匹配到404去

image-20220303104039713

3. 编程式导航

params 不能与 path 一起使用,而应该使用name(命名路由)

<template>
  <router-view></router-view>
</template>
<script>
import { useRoute, useRouter } from "vue-router"

export default {
  setup() {
    const route = useRoute()
    const router = useRouter()

    // // query编程式导航传参
    // router.push({
    //   path: "/user/123",
    //   query: {
    //     id: 666
    //   }
    // })

    // params编程式导航传参
    router.push({
      name: "user",            // 需要使用命名路由
      params: {
        userid: 666
      }
    })
  }
}
</script>

3.1 替换当前位置

不会向 history添加新纪录,而是替换当前的记录

声明式

<router-link to="/home" replace>home</router-link>

编程式

router.replace({
  path: '/home'
})

// 或
// router.push({
//   path: '/home',
//   replace: true
// })

4. 命名视图

需要同时同级展示多个视图,而不是嵌套展示时,命名视图就能够派上用场了

首先路由配置需要使用 components配置

const routes = [
  {
    path: "/",
    name: "home",
    components: {
      default: () => import("./views/First.vue"),
      second: () => import("./views/Second.vue"),
      third: () => import("./views/Third.vue")
    }
  }
];

使用 router-view时,添加上name属性即可

<router-view></router-view>
<router-view name="second"></router-view>
<router-view name="third"></router-view>

示例:

命名视图

5. 路由组件传参

首先可通过 route来实现路由传参,不过也可以通过 props配置来开启 props传参

import { createRouter, createWebHistory } from "vue-router";

const routes = [
  {
    path: "/user/:id",
    component: () => import("../components/User.vue"),
    props: true
  }
];

export default new createRouter({
  history: createWebHistory(),
  routes
});

通过 props获取参数

<template>
  <h2>User</h2>
  <p>{{ id }}</p>
</template>

<script setup>
const props = defineProps(["id"]);
</script>

<style>
</style>

image-20220303194719540

更多

参考链接:Vue Router

目录
相关文章
|
15天前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
134 2
|
4月前
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
571 0
|
4月前
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能
|
3月前
|
JavaScript 安全
在 Vue 中,如何在回调函数中正确使用 this?
在 Vue 中,如何在回调函数中正确使用 this?
111 0
|
3月前
|
人工智能 JSON JavaScript
VTJ.PRO 首发 MasterGo 设计智能识别引擎,秒级生成 Vue 代码
VTJ.PRO发布「AI MasterGo设计稿识别引擎」,成为全球首个支持解析MasterGo原生JSON文件并自动生成Vue组件的AI工具。通过双引擎架构,实现设计到代码全流程自动化,效率提升300%,助力企业降本增效,引领“设计即生产”新时代。
246 1
|
4月前
|
JavaScript 前端开发 开发者
Vue 自定义进度条组件封装及使用方法详解
这是一篇关于自定义进度条组件的使用指南和开发文档。文章详细介绍了如何在Vue项目中引入、注册并使用该组件,包括基础与高级示例。组件支持分段配置(如颜色、文本)、动画效果及超出进度提示等功能。同时提供了完整的代码实现,支持全局注册,并提出了优化建议,如主题支持、响应式设计等,帮助开发者更灵活地集成和定制进度条组件。资源链接已提供,适合前端开发者参考学习。
375 17
|
4月前
|
JavaScript 前端开发 UED
Vue 表情包输入组件实现代码及详细开发流程解析
这是一篇关于 Vue 表情包输入组件的使用方法与封装指南的文章。通过安装依赖、全局注册和局部使用,可以快速集成表情包功能到 Vue 项目中。文章还详细介绍了组件的封装实现、高级配置(如自定义表情列表、主题定制、动画效果和懒加载)以及完整集成示例。开发者可根据需求扩展功能,例如 GIF 搜索或自定义表情上传,提升用户体验。资源链接提供进一步学习材料。
213 1
|
JavaScript 测试技术 容器
Vue2+VueRouter2+webpack 构建项目
1). 安装Node环境和npm包管理工具 检测版本 node -v npm -v 图1.png 2). 安装vue-cli(vue脚手架) npm install -g vue-cli --registry=https://registry.
1196 0
|
6月前
|
JavaScript
vue实现任务周期cron表达式选择组件
vue实现任务周期cron表达式选择组件
770 4
|
5月前
|
JavaScript 数据可视化 前端开发
基于 Vue 与 D3 的可拖拽拓扑图技术方案及应用案例解析
本文介绍了基于Vue和D3实现可拖拽拓扑图的技术方案与应用实例。通过Vue构建用户界面和交互逻辑,结合D3强大的数据可视化能力,实现了力导向布局、节点拖拽、交互事件等功能。文章详细讲解了数据模型设计、拖拽功能实现、组件封装及高级扩展(如节点类型定制、连接样式优化等),并提供了性能优化方案以应对大数据量场景。最终,展示了基础网络拓扑、实时更新拓扑等应用实例,为开发者提供了一套完整的实现思路和实践经验。
545 77

热门文章

最新文章