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

动态路由匹配

### 笔记

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

  }

];

```

相关文章:

  • 【计算机视觉】OpenCV实战项目: opencv-text-deskew:实时文本图像校正
  • 【高并发内存池】从零到一的项目之centralcache整体结构设计及核心实现
  • 第五节:对象与原型链:JavaScript 的“类”与“继承”
  • NoMachine 将虚拟显示器改为物理显示器
  • 【nestjs】一般学习路线
  • 常见降维算法分析
  • Java游戏服务器开发流水账(3)游戏数据的缓存简介
  • spark缓存-persist
  • 算法与数据结构 - 二叉树结构入门
  • 【HarmonyOS NEXT+AI】问答05:ArkTS和仓颉编程语言怎么选?
  • 使用 React Native实现鸿蒙开发的详细方案
  • 双端口ram与真双端口ram的区别
  • 解决 MySQL 数据库无法远程连接的问题
  • BLURRR剪辑软件免费版:创意剪辑,轻松上手,打造个性视频
  • Kubernetes Gateway API 部署详解:从入门到实战
  • Django ORM: values() 和 annotate() 方法详解
  • 排序算法-归并排序
  • istio in action之Gateway流量入口与安全
  • OpenHarmony平台驱动开发(十一),PIN
  • 01.three官方示例+编辑器+AI快速学习webgl_animation_keyframes
  • 中国社科院:网文市场超430亿元,作者破3000万人
  • 国家出口管制工作协调机制办公室部署开展打击战略矿产走私出口专项行动
  • 大四本科生已发14篇SCI论文?重庆大学:成立工作组核实
  • 少年中国之少年的形塑
  • 深圳下调公积金利率,209万纯公积金贷款总利息减少9.94万
  • 习近平向“和平薪火 时代新章——纪念中国人民抗日战争和苏联伟大卫国战争胜利80周年中俄人文交流活动”致贺信