路由的钩子函数总结有6个
全局的路由钩子函数:beforeEach、afterEach
单个的路由钩子函数:beforeEnter
组件内的路由钩子函数:beforeRouteEnter、beforeRouteLeave、beforeRouteUpdate
模块一:全局导航钩子函数
1.vue router.beforeEach(全局前置守卫)
beforeEach的钩子函数,它是一个全局的before 钩子函数,
(beforeEach)意思是在 每次每个路由改变的时候都得执行一遍。
它的三个参数:
to: (Route路由对象) 即将要进入的目标 路由对象 to对象下面的属性: path params query hash fullPath matched name meta(在matched下,可是本例能够直接用)
from: (Route路由对象) 当前导航正要离开的路由
next: (Function函数) 必定要调用该方法来 resolve 这个钩子。 调用方法:next(参数或者空) ***
使用的场景:当登陆的时候(存在权限的时候),咱们须要在router文件下的index.js中写上如下的代码:
router.beforeEach((to, from, next) => {
<!--存放的token或者判断的标识(这里写的是一个树形结构的菜单为例 menuTree是个数组)-->
let menuTree = JSON.parse(sessionStorage.getItem('menuTree'));
if (from.name == null || to.name == "Login") {
next();
} else {
next({
path: '/login',
query: {redirect: to.fullPath}//将跳转的路由path做为参数,登陆成功后跳转到该路由
})
或者:(根据项目需求)
<!--if (menuTree != null) {-->
<!-- if (to.fullPath == '/EnergyBox') {-->
<!-- next({-->
<!-- path: '/Login'-->
<!-- })-->
<!-- }-->
<!-- next();-->
} else {
next({
path: '/Login'
})
}
}
})
next(无参数的时候): 进行管道中的下一个钩子,若是走到最后一个钩子函数,
那么导航的状态就是 confirmed (确认的)
next('/') 或者 next({ path: '/' }): 跳转到一个不一样的地址。当前的导航被中断,而后进行一个新的导航。
模块二:路由独享的守卫(路由内钩子)
你能够在路由配置上直接定义 beforeEnter 守卫:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
这些守卫与全局前置守卫的方法参数是同样的。
模块三:组件内的守卫(组件内钩子)
一、beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave
const Foo = {
template: `...`,
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 由于当钩子执行前,组件实例还没被建立
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,可是该组件被复用时调用
// 举例来讲,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 因为会渲染一样的 Foo 组件,所以组件实例会被复用。而这个钩子就会在这个状况下被调用。
// 能够访问组件实例 `this`
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
// 能够访问组件实例 `this`
}
使用场景:当一个组件中有一个定时器时, 在路由进行切换的时候, 可以使用beforeRouteLeave将定时器进行清楚, 以避免占用内存:
beforeRouteLeave (to, from, next) {
window.clearInterval(this.timer) //清楚定时器
next()
}
复制代码