起步

模块安装及引入

使用 npm 命令下载 Vue Router 模块。

  1. npm install vue-router

然后新建文件 router/index.js,在文件内添加以下内容以引入该模块。

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

创建路由实例对象

  1. const routes = [{
  2. path: '/',
  3. name: 'Home',
  4. component: () => import('@/views/Home.vue')
  5. }, {
  6. path: '/about',
  7. name: 'About',
  8. component: () => import('@/views/About.vue')
  9. }, {
  10. // ... 省略
  11. }]
  12. const router = new VueRouter({
  13. mode: 'history', // 选用 history 模式时使用
  14. base: process.env.BASE_URL,
  15. routes
  16. })
  17. export default router

也可以简化写法以减少代码量。

在 main.js 中导入路由实例

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

动态路由匹配

如果存在一个组件 User,对于 id 不同的各个用户,都需要使用这个组件进行渲染,那么可以在 Vue Router 的路由路径中使用动态路由匹配来达到这个效果。

  1. const router = new VueRouter({
  2. routes: [{
  3. path: '/user/:id', // 动态路径参数以 ':' 开头
  4. component: User
  5. }]
  6. })

动态路径参数使用冒号 : 标记,当路由匹配时,参数值会被设置到 this.$route.params,可以在每个组件内使用。

如果要匹配任意路径,通常使用通配符 *,目的是为了匹配客户端 404 错误。

匹配优先级:当同一个路径匹配多个路由时,匹配的优先级就按照路由的定义顺序:谁先定义,谁的优先级就最高。因此,含有通配符的路由应该在最后定义。

嵌套路由

一个组件同样可以包含自己的嵌套 <router-view>,这就是嵌套路由。要实现嵌套路由,需要在 Vue Router 的参数中使用 children 配置,这样也可以实现路由的多层嵌套。

  1. const router = new VueRouter({
  2. routes: [{
  3. path: '/user/:id', component: User,
  4. children: [{
  5. // 当 /user/:id 匹配成功,UserHome 会被渲染在 User 的 <router-view> 中
  6. path: '',
  7. component: UserHome
  8. },{
  9. // 当 /user/:id/profile 匹配成功,UserProfile 会被渲染在 User 的 <router-view> 中
  10. path: 'profile',
  11. component: UserProfile
  12. }, {
  13. // 当 /user/:id/posts 匹配成功,UserPosts 会被渲染在 User 的 <router-view> 中
  14. path: 'posts',
  15. component: UserPosts
  16. }]
  17. }]
  18. })

编程式导航

除了使用 <router-link> 来定义导航链接,我们还可以借助 router 的实例方法编程实现。

  1. this.$router.push('home')
  2. this.$router.push({ path: 'home' })
  3. this.$router.push({ name: 'user', params: { userId: '123' }}) // 动态路由匹配
  4. this.$router.push({ path: 'register', query: { plan: 'private' }}) // 带查询参数

设置动态路由匹配时,需要使用 name 属性,使用 path 属性则 params 不生效。同样的规则也适用于 router-link 组件。

$router.replace() 有着相同的作用,区别在于它不会添加新的历史记录,而是进行替换。

$router.go(n) 的参数是一个整数,意思是根据历史记录前进或者后退多少步,类似于window.history.go(n)