https://router.vuejs.org/zh/installation.html
安装
直接下载 / CDN
NPM
npm install vue-router
- 在一个模块化工程中使用它,必须要通过 Vue.use() 明确地安装路由功能
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
构建开发版
介绍
起步
HTML
<!-- 通过传入 `to` 属性指定链接. -->
<!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
<router-link to="/foo">Go to Foo</router-link>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
JavaScript
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
const router = new VueRouter({
routes
})
- 通过注入路由器,我们可以在任何组件内通过 this.$router 访问路由器,也可以通过 this.$route 访问当前路由
- this.$router 和 router 使用起来完全一样
- 当 <router-link> 对应的路由匹配成功,将自动设置 class 属性值 .router-link-active。
动态路由匹配
- “动态路径参数”(dynamic segment)
- 当匹配到一个路由时,参数值会被设置到 this.$route.params
const router = new VueRouter({
routes: [
// 动态路径参数 以冒号开头
{ path: '/user/:id', component: User }
]
})
- 可以在一个路由中设置多段“路径参数”,对应的值都会设置到 $route.params 中
/user/:username/post/:post_id /user/evan/post/123 { username: 'evan', post_id: '123' }
响应路由参数的变化
- 当使用路由参数时,例如从 /user/foo 导航到 /user/bar,原来的组件实例会被复用。
- 这也意味着组件的生命周期钩子不会再被调用。
- 复用组件时,想对路由参数的变化作出响应的话,你可以简单地 watch (监测变化) $route 对象
const User = {
template: '...',
watch: {
'$route' (to, from) {
// 对路由变化作出响应...
}
}
}
- 或者使用 2.2 中引入的 beforeRouteUpdate 导航守卫
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
捕获所有路由或 404 Not found 路由
{
// 会匹配所有路径
path: '*'
}
{
// 会匹配以 `/user-` 开头的任意路径
path: '/user-*'
}
- 当使用通配符路由时,请确保路由的顺序是正确的,也就是说含有通配符的路由应该放在最后(404错误页面)
- 如果你使用了History 模式,请确保正确配置你的服务器。
- 当使用一个通配符时,$route.params 内会自动添加一个名为 pathMatch 参数。它包含了 URL 通过通配符被匹配的部分
// 给出一个路由 { path: '/user-*' }
this.$router.push('/user-admin')
this.$route.params.pathMatch // 'admin'
// 给出一个路由 { path: '*' }
this.$router.push('/non-existing')
this.$route.params.pathMatch // '/non-existing'
高级匹配模式
- vue-router 使用 path-to-regexp 作为路径匹配引擎,所以支持很多高级的匹配模式 https://github.com/pillarjs/path-to-regexp/tree/v1.7.0
- vue-router 怎么使用这类匹配 https://github.com/vuejs/vue-router/blob/dev/examples/route-matching/app.js
匹配优先级
- 同一个路径可以匹配多个路由,此时,匹配的优先级就按照路由的定义顺序:谁先定义的,谁的优先级就最高。