文章目录
一、全局前置beforeEach
当 Local Storage 里面存储的 name 是 zhangsan 的时候, 点击消息才显示消息内容
1. 全局前置beforeEach
给router添加一个路由守卫 beforeEach
语法 :
router.beforeEach((to, from, next)=>{})
作用 : 初始化的时候 和 在每一次路由切换之前调用beforeEach里面的函数
参数 :
- to : 目标路由
- from : 跳转前的路由
- next : 放行
2. 实现
二、需求二
如果有很多个路径都需要做出判断以后才跳转, 就需要写很多判断的代码, 判断结构就会很复杂
这时需要判断的路由里面就可以放一个meta标签
meta标签提供关于HTML文档的元数据 (元数据指用来描述数据的数据)
这时就可以使用meta里面的标记字段进行判断
三、全局后置守卫 afterEach
afterEach 和 beforeEach 使用方法基本一致.
区别就是afterEach没有next这个参数
1. 修改title为自己的title
给每个路由指定自己的title名称
const router = new VueRouter({
routes: [
{
name: 'home',
path: '/home',
component: Home,
meta: {
title: "首页"
},
children: [
{
name: "xiaoxi",
path: 'message',
component: Message,
meta: {
title: "消息"
},
children: [
{
name: 'xiangqing',
path: 'detail',
component: Detail,
meta: {
isAuth: true,
title: "消息详情"
}
}
]
}
]
},
{
path: '/about',
component: About,
meta: {
title: "关于"
}
}
]
})
在 beforEach里面修改title名
router.afterEach((to, from) => {
document.title = to.meta.title || "测试"
})
四、组件内守卫
1. beforeRouteEnter
通过路由规则, 进入该组件时被调用
1. beforeRouteLeave
通过路由规则, 离开该组件时被调用