当前位置: 首页 > backend >正文

动态路由匹配

### 笔记

1. 路由跳转3种

- RouterLink给to属性指定地址进行跳转

- dom元素中,事件中使用`$router.push('/')

- js编程方式跳转:

    1. js中先拿到路由实例

    2. router.push()


 

#### 动态路由匹配

```js

const User = {

  template: '<div>User {{ $route.params.id }}</div>'

}

const router = new VueRouter({

  routes: [

    { path: '/user/:id', component: User }

  ]

})

```

#### 响应路由参数的变化

1. **使用 `watch` 监听 `$route` 对象**:

```js

const User = {

  template: '...',

  watch: {

    $route(to, from) {

      // 对路由变化作出响应

      console.log('路由参数变化:', to.params);

    }

  }

}

```

2. **使用 `beforeRouteUpdate` 导航守卫**(Vue Router 2.2+):

```js

const User = {

  template: '...',

  beforeRouteUpdate(to, from, next) {

    // 在路由更新前响应变化

    console.log('路由更新:', to.params);

    next();

  }

}

```

#### 使用通配符 `*` 来捕获所有路由或设置 404 页面。

```js

const routes = [

  {

    path: '/:pathMatch(.*)', // 捕获所有路由

    name: 'NotFound',

    component: NotFound

  },

  {

    path: '/user-*', // 匹配以 `/user-` 开头的任意路径

    component: UserGeneric

  }

];

```

- **通配符路由**:`path: '*'` 通常用于客户端 404 错误。

- **`pathMatch` 参数**:通配符匹配的部分会自动添加到 `$route.params.pathMatch` 中。

```js

this.$router.push('/user-admin');

console.log(this.$route.params.pathMatch); // 'admin'

this.$router.push('/non-existing');

console.log(this.$route.params.pathMatch); // '/non-existing'

```

#### 高级匹配模式

- Vue Router 支持许多高级匹配模式,如可选参数、零或多个参数、一个或多个参数,甚至自定义的正则匹配规则

```js

const routes = [

  {

    path: '/chapters*', // 匹配 `/chapters`, `/chapters/one`, `/chapters/one/two`, 等

    component: Chapters

  },

  {

    path: '/chapters+', // 匹配 `/chapters/one`, `/chapters/one/two`, 等,但不匹配 `/chapters`

    component: Chapters

  },

  {

    path: '/users/:id?', // 可选参数,匹配 `/users` 和 `/users/42`

    component: Users

  }

];

```

http://www.xdnf.cn/news/5073.html

相关文章:

  • 家庭NAS怎么选?
  • 软考高级系统架构设计师备考分享:操作系统核心知识点整理
  • QML AnimatedImage组件详解
  • SAP note 3565626 : Baltimore CyberTrust 根证书即将过期
  • AGV通信第3期|AGV集群智能应急响应系统:从故障感知到快速恢复
  • 微信小程序地图缩放scale隐性bug
  • 记忆化搜索
  • workbench fluent动画
  • 2025年现代职业教育质量提升计划(植保无人机实训室)解决方案
  • 【基础】模型上下文协议(Model Context Protocol, MCP)根本原理与工作机制详解
  • “点对点通信(Point-to-Point)”和“端对端通信(End-to-End)”
  • 高性能编程相关
  • 机器学习第三讲:监督学习 → 带答案的学习册,如预测房价时需要历史价格数据
  • auto推导类型原则
  • 【深度学习新浪潮】苹果在显示算法技术上的研发进展调研
  • 多模态AI新纪元:Vertex AI Gemini与Spring AI深度集成实践
  • 汽车租赁|基于Java+vue的汽车租赁系统(源码+数据库+文档)
  • [春秋云镜] Brute4Road 仿真场景
  • 用 Rust 搭建一个优雅的多线程服务器:从零开始的详细指南
  • 突破跨界传输瓶颈:Zynq OCM与DDR核间数据共享性能深度调优
  • 安装数据库记录
  • LeetCode百题刷001双指针·快慢指针
  • Kafka单机版安装部署
  • 什么是信号完整性?
  • VBA高级应用30例应用4:利用屏蔽事件来阻止自动运行事件
  • Tomcat的`context.xml`配置详解!
  • 嵌入式系统架构验证工具:AADL Inspector v1.10 全新升级
  • 1、mongodb-- BSON 学习和JSON性能对比
  • 新一代电动门“攻克”行业痛点,远峰科技打造“智能出入”新标杆
  • ApplicationEventPublisher 深度解析:Spring 事件驱动模型的核心