- 路由结构为
/user/:id
时,当用户从/user/foo
导航到/user/bar
时,相同的组件实例将被重用,它还意味着不会调用组件的生命周期挂钩。要对同一组件中的参数更改做出反应,您只需观察$route
对象,或者使用beforerouteupdate
:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
// or
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
- 基于路径的动态过渡:可以根据目标路由和当前路由之间的关系确定要动态使用的转换:
<!-- use a dynamic transition name -->
<transition :name="transitionName">
<router-view></router-view>
</transition>
// then, in the parent component,
// watch the `$route` to determine the transition to use
watch: {
'$route' (to, from) {
const toDepth = to.path.split('/').length
const fromDepth = from.path.split('/').length
this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
}
}
// or
beforeRouteUpdate (to, from, next) {
const toDepth = to.path.split('/').length
const fromDepth = from.path.split('/').length
this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
next()
},
- 滚动行为
scrollBehavior
:需要浏览器支持history.pushState
,当使用后退/前进按钮导航时,返回savedposition将去到页面原来定位的位置,以模拟原生的行为。
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return desired position
if (savedPosition) {
return savedPosition
} else {
return { x: 0, y: 0 }
}
}
})
- 优化打包,懒加载路径:如果我们可以将每个路由的组件分割成单独的块,并且只在访问路由时加载它们,那么效率会更高。
new Router({
routes: [
{
path: '/',
component: resolve => require(['pages/index.vue'], resolve)
},
]
})
网友评论