起步
模块安装及引入
使用 npm 命令下载 Vue Router 模块。
npm install vue-router
然后新建文件 router/index.js
,在文件内添加以下内容以引入该模块。
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter);
创建路由实例对象
const routes = [{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue')
}, {
path: '/about',
name: 'About',
component: () => import('@/views/About.vue')
}, {
// ... 省略
}]
const router = new VueRouter({
mode: 'history', // 选用 history 模式时使用
base: process.env.BASE_URL,
routes
})
export default router
也可以简化写法以减少代码量。
在 main.js 中导入路由实例
import router from './router'
new Vue({
router,
render: h => h(App)
}).$mount('#app')
动态路由匹配
如果存在一个组件 User
,对于 id 不同的各个用户,都需要使用这个组件进行渲染,那么可以在 Vue Router 的路由路径中使用动态路由匹配来达到这个效果。
const router = new VueRouter({
routes: [{
path: '/user/:id', // 动态路径参数以 ':' 开头
component: User
}]
})
动态路径参数使用冒号 :
标记,当路由匹配时,参数值会被设置到
this.$route.params
,可以在每个组件内使用。
如果要匹配任意路径,通常使用通配符 *
,目的是为了匹配客户端 404 错误。
匹配优先级:当同一个路径匹配多个路由时,匹配的优先级就按照路由的定义顺序:谁先定义,谁的优先级就最高。因此,含有通配符的路由应该在最后定义。
嵌套路由
一个组件同样可以包含自己的嵌套 <router-view>
,这就是嵌套路由。要实现嵌套路由,需要在 Vue Router 的参数中使用 children
配置,这样也可以实现路由的多层嵌套。
const router = new VueRouter({
routes: [{
path: '/user/:id', component: User,
children: [{
// 当 /user/:id 匹配成功,UserHome 会被渲染在 User 的 <router-view> 中
path: '',
component: UserHome
},{
// 当 /user/:id/profile 匹配成功,UserProfile 会被渲染在 User 的 <router-view> 中
path: 'profile',
component: UserProfile
}, {
// 当 /user/:id/posts 匹配成功,UserPosts 会被渲染在 User 的 <router-view> 中
path: 'posts',
component: UserPosts
}]
}]
})
编程式导航
除了使用 <router-link>
来定义导航链接,我们还可以借助 router 的实例方法编程实现。
this.$router.push('home')
this.$router.push({ path: 'home' })
this.$router.push({ name: 'user', params: { userId: '123' }}) // 动态路由匹配
this.$router.push({ path: 'register', query: { plan: 'private' }}) // 带查询参数
设置动态路由匹配时,需要使用
name
属性,使用path
属性则params
不生效。同样的规则也适用于router-link
组件。
$router.replace()
有着相同的作用,区别在于它不会添加新的历史记录,而是进行替换。
$router.go(n)
的参数是一个整数,意思是根据历史记录前进或者后退多少步,类似于window.history.go(n)
。