什么是钩子函数?
主要是给使用者在路由发生变化时进行一些特殊的处理而定义的函数。
为什么要使用路由的钩子函数?
在路由跳转时,需要一些权限判断或者其他操作。
Vue.beforeEach(function(to, from, next) {
// 在跳转之前执行
})
Vue.afterEach(function(to, from) {
// 在跳转之后执行
})
- to: 即将要进入的目标 路由对象。
- from: 当前导航正要离开的路由。
- next: 调用该方法 resolve 钩子函数(必须调用,否则钩子不会被 resolve),执行结果依赖 next 方法调用参数。
-
next()
进行管道中的下一个钩子。若全部钩子执行完,则导航状态为 confirmed (确认); -
next(false)
中断当前导航。浏览器 url 改变 (可能是用户手动或浏览器后退按钮),此时 url 会重置到 from 路由对应的地址; -
next('/')
next({ path: '/' })
跳转到一个不同地址。中断当前导航,进行一个新的导航; -
next(error)
传入next 参数是一个 error 实例,导航会被终止,该错误会被传递给 router.onError() 注册过的回调。
开发实例代码
用户访问一些页面时,需要判断是否有权限访问 / 判断是否已登录。
router.js
import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
Vue.use(Router)
const router = new Router({
routes: [
{ // 首页
path: '/',
component: () => import('@/pages/Index/template.vue')
// 当访问到页面时才异步引入对应的资源
// 防止一开始引入全部资源
// 不仅速度慢而且如果别的页面用户不去访问会造成资源浪费
},
{ // 登录页
path: '/Login',
component: () => import('@/pages/Login/template.vue')
},
{ // 注册页
path: '/Register',
component: () => import('@/pages/Register/template.vue')
},
{ // 详情页
path: '/Detail/:blogId',
component: () => import('@/pages/Detail/template.vue')
},
{ // 我的页面
path: '/My',
component: () => import('@/pages/My/template.vue'),
meta: { requiresAuth: true }
},
{ // 用户页面
path: '/User/userId',
component: () => import('@/pages/User/template.vue')
}
]
})
router.beforeEach((to, from, next) => {
// 即将进入的目标路由对象 是否存在 meta.requiresAuth 为 true
// 如果存在,则需要判断是否已经登录,比如我的个人页面
if (to.matched.some(record => record.meta.requiresAuth)) {
// 调用 store actions 检查是否已经登录
store.dispatch('checkLogin').then(isLogin => {
if(!isLogin) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
})
} else {
next() // 确保一定要调用 next
}
})
export default router
login.js
this.login({ username: this.username, password: this.password })
.then(() => {
// 登录成功跳转到导航目标路由,如果没有则跳转至首页
this.$router.push({ path: this.$route.query.redirect || '/' })
})
网友评论