1.带参数路由
2.两个路由都渲染同个组件
复用组件时,想对路由参数的变化作出响应,watch (监测变化)
onAbort: 导航到相同的路由、或在当前导航完成之前导航到另一个不同的路由
13.别名
routers:[
{path:'/user/:id',name:'user',component:User}
]
使用参数:
$router.params.id
2.两个路由都渲染同个组件
复用组件时,想对路由参数的变化作出响应,watch (监测变化)
watch{
'route'(to,from){
}
}
或者使用beforeRouteUpdate (目标路由和当前路由相同,只是参数发生变化)
beforeRouteUpdate(to,from,next){
}
3.匹配的优先级就按照路由的定义顺序:谁先定义的,谁的优先级就最高。
4.在组件中嵌套路由 <router-view></router-view>
routes: [
{ path: '/user/:id', component: User,
children: [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path: 'profile',
component: UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path: 'posts',
component: UserPosts
}
]
}
]
5.<router-link></router-link>代替a连接
6.编程式导航router.push('index') //字符串
router.push({ path: 'index' }) //路由path
router.push({ path: '/user/${id}'}) //带参路由
router.push({ name: 'index' ,params: { name :'1233'}}) //路由中带参数,需要提供路由名称
router.push({ path: 'user', query:{id:'1'}}) //带查询参数
7.onComplete和onAbort
onComplete:导航完成后调用(在所有的异步钩子被解析之后)onAbort: 导航到相同的路由、或在当前导航完成之前导航到另一个不同的路由
用法:router.replace(location, onComplete?, onAbort?)
8.router.replace和router.push
作用相同,区别:router.replace是替换和当前的history记录而不产生新的history
9.回退
router.go(1) //history.forward()
router.go(-1) //history.back()
goBack(){
window.history.length >1 ? this.$router.go(-1) : this.$router.push('/')
}
10.命名路由
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link> //声明式
router.push({ name: 'user', params: { userId: 123 }}) //编程式
11.命名视图
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
12.重定向
- 路径path
routes: [
{ path: '/a', redirect: '/b' }
]
- 命名路由
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
- 方法动态返回
routes: [
{ path: '/a', redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}}
]
13.别名
routes: [
{ path: '/a', component: A, alias: '/b' }
]
14.解耦合
routes: [
{ path: '/user/:id', component: User, props: true },
// 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
15.props 函数模式
routes: [
{ path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
]
URL /search?q=vue 会将 {query: 'vue'} 作为属性传递给 SearchUser 组件。