大家好,又见面了,我是你们的朋友全栈君。
路由跳转的时候,我们需要做一些权限判断或者其他操作。这个时候就需要使用路由钩子函数。
定义:路由钩子主要是给使用者在路由发生变化时进行一些特殊的处理而定义的函数。
总体来讲,vue
提供三大类钩子,
两种函数:
Vue.beforeEach(function(to,form,next){}) /*在跳转之前执行*/
Vue.afterEach(function(to,form))/*在跳转之后判断*/
顾名思义,它是对全局有效的一个函数。
router.beforeEach((to, from, next) => {
let token = router.app.$storage.fetch("token");
let needAuth = to.matched.some(item => item.meta.login);
if(!token && needAuth) return next({
path: "/login"});
next();
});
beforeEach
函数有三个参数:
to
:router
即将进入的路由对象;from
:当前导航即将离开的路由;next
:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed
(确认的);否则为false
,终止导航。注:afterEach()
不用传next()
函数。
顾名思义,它是写在某个路由里的函数,本质上跟组件内函数没有区别。
const router = new VueRouter({
routes: [
{
path: '/login',
component: Login,
beforeEnter: (to, from, next) => {
// ...
},
beforeLeave: (to, from, next) => {
// ...
}
}
]
})
注意:这里说的是路由组件!
路由组件 属于 组件,但组件 不等同于 路由组件! 所谓的路由组件:直接定义在router
中component
处的组件。如:
var routes = [
{
path:'/home',
component:home,
name:"home"
}
]
在子组件中调用路由钩子函数是无效的。
在官方文档上是这样定义的:
可以在路由组件内直接定义以下路由导航钩子:
beforeRouteEnter
beforeRouteUpdate
(2.2 新增)beforeRouteLeave
这里简单说下钩子函数用法:它是和data
,methods
平级的。
beforeRouteLeave(to, from, next) {
next()
},
beforeRouteEnter(to, from, next) {
next()
},
beforeRouteUpdate(to, from, next) {
next()
},
data:{
},
method: {
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/149043.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有