$router 访问路由实例整个路由配置
new Vue({
router
}).$mount('#app')
$route 访问路由对象当前 URL 解析得到的信息
配置路由模式:
hash: 使用 URL hash 值来作路由。支持所有浏览器,包括不支持 HTML5 History Api 的浏览器。这种模式充分利用history.pushStateAPI 来完成 URL 跳转而无须重新加载页面。history: 依赖 HTML5 History API 和服务器配置。查看 HTML5 History 模式。abstract: 支持所有 JavaScript 运行环境,如 Node.js 服务器端。如果发现没有浏览器的 API,路由会自动强制进入这个模式。
当 <router-link> 对应的路由匹配成功,将自动设置 class 属性值 .router-link-active
动态路由
优先级:谁先定义的,谁的优先级就最高。
// https://github.com/vuejs/vue-router/blob/dev/examples/route-matching/app.js
{ path: '/' },
// params are denoted with a colon ":"
{ path: '/params/:foo/:bar' },
// a param can be made optional by adding "?"
{ path: '/optional-params/:foo?' },
// a param can be followed by a regex pattern in parens
// this route will only be matched if :id is all numbers
{ path: '/params-with-regex/:id(\\d+)' },
// asterisk can match anything
{ path: '/asterisk/*' },
// make part of the path optional by wrapping with parens and add "?"
{ path: '/optional-group/(foo/)?bar' }
嵌套路由
/开头的嵌套路径会被当作根路径- 嵌套多层路由访问
/user时,可以提供一个空的子路由来实现 - 当使用路由参数时,例如从
/user/foo导航到/user/bar,原来的组件实例会被复用,你需要使用beforeRouteUpdate来响应这个变化 (比如抓取用户信息)
{
path: '/user/:id', component: User,
children: [
// 当 /user/:id 匹配成功,
// UserHome 会被渲染在 User 的 <router-view> 中
{ path: '', component: UserHome },
// ...其他子路由
]
}
编程式导航
router.push(向 history 栈添加一个新的记录)、 router.replace (替换掉当前的 history 记录)和 router.go(向前或者后退多少步) 跟 window.history.pushState、 window.history.replaceState 和 window.history.go
// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
// 注意:如果提供了 path,params 会被忽略,这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user
// 提供路由的 name 或手写完整的带有参数的 path
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
点击 <router-link :to="..."> 等同于调用 router.push(...)。
命名路由
{
path: '/user/:userId',
name: 'user',
component: User
}
命名视图
<!-- UserSettings.vue -->
<div>
<h1>User Settings</h1>
<NavBar/>
<router-view/>
<router-view name="helper"/>
</div>
<script>
{
path: '/settings',
// 你也可以在顶级路由就配置命名视图
component: UserSettings,
children: [{
path: 'emails',
component: UserEmailsSubscriptions
}, {
path: 'profile',
components: {
default: UserProfile,
helper: UserProfilePreview
}
}]
}
</script>
重定向
const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/b' },
{ path: '/a', redirect: { name: 'foo' }}
{ path: '/a', redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}}
]
})
路由别名(不是受限于配置的嵌套路由结构。)
/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样。
{ path: '/a', component: A, alias: '/b' }
路由传参
无状态参数
// 取代与 $route 的耦合
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
{ path: '/promotion/from-newsletter', component: Promotion, props: { id: 1 } }
// props 函数为无状态的
{ path: '/search', component: SearchUser, props: (route) => ({ id: route.id.q }) }
// 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
导航守卫
包括:全局的, 单个路由独享的, 或者组件级的
参数或查询的改变并不会触发进入/离开的导航守卫你可以通过观察 $route 对象来应对这些变化,或使用 beforeRouteUpdate 的组件内守卫。
过度动效
<transition :name="transitionName">
<router-view></router-view>
</transition>
<script>
// 接着在父组件内
// watch $route 决定使用哪种过渡
watch: {
'$route' (to, from) {
const toDepth = to.path.split('/').length
const fromDepth = from.path.split('/').length
this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
}
}
</script>
路由记录
{
path: 'bar',
component: Bar,
// a meta field
meta: { requiresAuth: true }
}
// $route.matched 来检查路由记录中的 meta 字段。
// 当前路由的 $route.hash(#值) /a#id (#id)
滚动行为
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
// return 期望滚动到哪个的位置
return { x: 0, y: 0 }
}
if (to.hash) {
return {
selector: to.hash
}
}
}
})
引用:
VueRouter