写在前面

在上篇博客 前端路由 中是根据原生的 Web API 手动构建的前端路由器。在 Vue 框架中,Vue 官方有提供对应的路由管理器,就是 Vue Router。无论是哪种前端路由管理工具,实现思路基本是一致的。因此在学习 Vue Router 的使用方法时,应从 路由表、路由链接、路由内容等 进行记忆。

1. 是什么

Vue Router 是 vue.js 官方的路由管理器。

2. 基本用法

2.1 安装 vue-router 到项目中

安装:
yarn add vue-router

引入:

  1. import VueRouter from 'vue-router'
  2. Vue.use(VueRouter)

2.2 定义路由表

  1. const routes = [
  2. {path: '/a', component: A},
  3. {path: '/b', component: B}
  4. ]

2.3 创建 VueRouter 实例

  1. const router = new VueRouter({
  2. routes,
  3. mode: 'history' //路由模式选择,默认是 hash
  4. })

2.4 将路由注入应用

  1. new Vue({
  2. render: h => h(App),
  3. router
  4. }).$mount('#app')

2.5 定义路由路口(a链接位置)

  1. <router-link to="/a">go to A</router-link>
  2. <router-link to="/b">go to B</router-link>

2.6 定义路由出口(内容展示位置)

  1. <router-view></router-view>

2.7 定义默认路由和404路由

  1. const routes = [
  2. //默认路由,匹配 /
  3. {path: '/', component: A},
  4. {path: '/a', component: A},
  5. {path: '/b', component: B},
  6. //使用通配符放在路由表最后匹配404路由
  7. {path: '*', component: NotFound}
  8. ]

3. VueRouter 实例的使用

将 VueRouter 实例 router 注入到 Vue 应用中后,VueRouter 内部做了一些操作,将 router 实例相关的信息定义在了 Vue 的原型上,以便于所有 Vue 组件内部都可以访问到 router 实例。

![](https://g.yuque.com/gr/latex?router%20%EF%BC%9A%E5%88%9B%E5%BB%BA%E7%9A%84%E8%B7%AF%E7%94%B1%E5%AE%9E%E4%BE%8B%EF%BC%8C%E5%8C%85%E5%90%AB%E6%89%80%E6%9C%89%E8%B7%AF%E7%94%B1%E4%BF%A1%E6%81%AF%0A#card=math&code=router%2A%2A%20%EF%BC%9A%E5%88%9B%E5%BB%BA%E7%9A%84%E8%B7%AF%E7%94%B1%E5%AE%9E%E4%BE%8B%EF%BC%8C%E5%8C%85%E5%90%AB%E6%89%80%E6%9C%89%E8%B7%AF%E7%94%B1%E4%BF%A1%E6%81%AF%0A%2A%2A&id=nqr9A)route:当前路由信息对象

4. 动态路由

在路由表中将 path 属性参数的前面加 :

  1. const routes = [
  2. {path: '/', component: B},
  3. //动态路由
  4. {path: '/a/:id', component: A},
  5. {path: '/b', component: B},
  6. {path: '*', component: NotFound}
  7. ]

这样一来, /a/1/a/2 都会显示组件 A

  1. //A.vue
  2. <template>
  3. <div>
  4. 我是 A 组件的内容,我收到的参数为 {{$route.params.id}}
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. mounted(){
  10. console.log(this.$route.params.id)
  11. },
  12. watch: {
  13. $route(to, from){
  14. console.log(this.$router)
  15. console.log(`路由变了,从 ${from.params.id} 变到了 ${to.params.id}`)
  16. }
  17. }
  18. }
  19. </script>

5. 嵌套路由

Vue Router 是在每一个路由配置对象里添加了一个 children 属性,用于嵌套路由。使用方法如下:

  1. const routes = [
  2. {path: '/', component: A, children: [
  3. {path: '', component: A0},
  4. ]},
  5. {path: '/a', component: A, children: [
  6. //匹配''空白字符是指在 url 为 /a 时 A.vue 中 RouterView 显示的内容
  7. {path: '', component: A0},
  8. {path: '1', component: A1},
  9. {path: '2', component: A2}
  10. ]},
  11. {path: '/b', component: B},
  12. {path: '*', component: NotFound}
  13. ]
  1. //A.vue
  2. <template>
  3. <div>
  4. 我是 A 组件的内容
  5. <router-link to="/a/1">go to A1</router-link>
  6. <router-link to="/a/2">go to A2</router-link>
  7. <router-view></router-view>
  8. </div>
  9. </template>