监听/控制路由的切换
- 状态修改与切换
- 跳转的鉴权
导航守卫 | Vue Router (opens new window)
# 案例1 使用导航守卫功能实现标题的修改
// VueRouter对象
const routes = [
{
path: '/home',
component: Home,
meta: {
title: '首页'
},
children: [
{
path: 'news',
component: HomeNews
},
{
path: 'message',
component: HomeMessage
}
]
},
{
path: '/profile',
component: Profile,
meta: {
title: '档案'
},
}
]
// 前置守卫(guard)
router.beforeEach((to, from, next) => {
// 从from跳转到to
document.title = to.matched[0].meta.title; // 使用导航守卫功能实现标题的修改
next()
})
# 使用 keep-alive 保留组件的缓存
keep-alive — Vue.js (opens new window)
<!-- Profile,User 不保留缓存 -->
<keep-alive exclude="Profile,User">
<router-view/>
</keep-alive>
activated
, deactivated
这两个生命周期函数,只有在 keep-alive
中才有效。