文章目录
一、需求
当点击到哪个模块的时候, 就把title修改为哪个模块的名字.
二、方法一 : 使用生命周期函数
created()
: 当组件被创建的时候回调created
函数mounted()
: 当组件被挂载到DOM上的时候回调mounted
函数updated()
: 当页面发生更新的时候回调updated
函数
<template>
<div>
<h3>
我是Home
</h3>
<router-link to="/home/news" tag="button">新闻</router-link>
<router-link to="/home/message" tag="button">消息</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'Home',
// 当组件被创建的时候修改title
created() {
document.title = '首页'
},
}
</script>
<style>
.router-link-active {
color: red;
}
</style>
这样的做法有一个弊端, 就是每个组件都需要添加created函数, 造成代码冗余
二、方法二 : 监听全局跳转
使用
router.beforeEach()
监听全局跳转
beforeEach()
函数里面接收一个函数, 函数又需要三个参数(to, from, next)
, 从from跳转到to
里面必须调用next()
方法, 否则将无法跳转
2.1 在路由里面添加源数据
const routes = [
{
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home,
meta: {
title: '首页'
},
children: [{
path: '',
redirect: '/home/news',
},
{
path: 'news',
component: HomeNews,
},
{
path: 'message',
component: HomeMessage,
}]
},
{
path: '/about',
component: About,
meta: {
title: '关于'
}
},
{
path: '/user/:userid',
component: User,
meta: {
title: '用户'
}
},
{
path: '/profile',
component: Profile,
meta: {
title: '配置'
}
}
]
2.2 从from跳转到to
router.beforeEach((to, from, next) => {
// 把源数据里面的title赋值给元素的title
document.title = to.matched[0].meta.title
next()
})
三、导航守卫
beforeEach()
也称为前置钩子 , 是全局导航守卫
除了beforeEach()
还有afterEach()
, 是全局后置钩子.
四、路由独享的守卫
可以在路由配置上直接定义 beforeEnter守卫
const routes = [
{
path: '/home',
component: Home,
meta: {
title: '首页'
},
beforeEnter: (to, from, next) => {
// ...
}
}
]
五、组件内的导航守卫
5.1 beforeRouterEnter()
beforeRouterEnter(to, from, next){
// 在渲染该组件的对应录用后被confirm前调用
// 不能获取组件实例 this
// 因为当守卫执行前, 组件实例还没被创建
}
5.2 beforeRouterUpdate()
beforeRouterUpdate(to, from, next){
// 在当前路由改变, 但是该组件被复用时调用
// 例如: 一个带有动态参数的路径, /foo/:id. 在/foo/1 和 /foo/2之间跳转的时候, 由于会渲染同样的Foo组件, 因此组件实例会被复用, 这个钩子就会在这个情况下被调用
// 可以访问组件实例 this
}
5.1 beforeRouterLeave()
beforeRouterLeave(to, from, next){
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 this
}