前言
路由守卫,又叫导航守卫:就是路由跳转过程中的一些钩子函数。路由跳转是一个大的过程,这个大的过程分为跳转前中后等等细小的过程,在每一个过程中都有一函数,这个函数能让你操作一些其他的事儿的时机,这就是导航守卫。
vue中路由守卫一共有三种:全局路由守卫,组件内路由守卫,router独享守卫
路由守卫的配置基本相同
一、 全局路由守卫
// 先在router的index.js中,使用VueRouter
Vue.use(VueRouter)
// 在路由的路径中,可以设置meta,以便进行一些守卫的判断,比如:
const routes = [
{
path: '/index',
component: Index,
meta: {
needLogin: true
}
}
]
// 然后实例化VueRouter
const router = new VueRouter({
// 是否设为哈希模式 hash history
// mode: 'history',
// 配置基路径
base: process.env.BASE_URL, // process.env是node.js的一种环境对象
// 守卫的范围
routes
})
// 接着 to 表示去哪的路由 from表示从哪来的路由 next表示一个回调函数
// next()//直接进to 所指路由
// next(false) //中断当前路由
// next('route') //跳转指定路由
// next('error') //跳转错误路由
router.beforeEach((to, from,next) => {
// 判断是否需要守卫
if (to.meta.needLogin){
// 通过请求即时判断登陆状态
myinfo().then(res=>{
// 登陆了
if (res.data.code==0){
// 直接放行
next()
}else {
// 没登陆 弹框提示 并跳转到登录、注册页面
Dialog.alert({
message: '请先登录',
}).then(() => {
// on close
});
next('/login')
}
})
}else {
next()
}
})
二、组件间路由
// 跟methods: {} 等同级别书写
// 在路由进入之前,组件实例还未渲染,所以无法获取this实例,只能通过vm来访问组件实例
beforeRouteEnter (to, from, next) {
next(
vm => {}
)
}
// 同一页面,刷新不同数据时调用
beforeRouteUpdate (to, from, next) {
next(
vm => {}
)
}
// 离开当前路由页面时调用
beforeRouteLeave (to, from, next) {
next(
vm => {}
)
}
三、router独享守卫
// 直接在routes中的路由里
const routes = [
{
path: '/index',
component: Index,
beforeEnter: (to, from, next) => {
next()
}
}
]