美文网首页
使用vue-router的beforeEach钩子里做登陆页面访

使用vue-router的beforeEach钩子里做登陆页面访

作者: 唐卡豆子 | 来源:发表于2018-09-05 00:23 被阅读0次

登陆页面路径 '/login'
首页路径 '/'
beforeEach钩子函数,是一个全局的before钩子函数。before each 在每一个路由改变的时候都执行一遍
处理页面访问权限验证,在login页面使用sessionStorage配合vuex

1.登陆页面

login(){
      this.$validator.validateAll().then(result=>{
        if(result){
          console.log("成功")
          this.$store.commit('login_in', this.mobile)
          // 跳转回被拦截前路径 或是 如果是直接访问login则跳回主页面
          this.$router.push(this.$route.query.redirect || '/')
        }
      })
    }

2.store.js 页面

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let store = new Vuex.Store({
  state:{
    accessToken:null
  },
  mutations:{
    login_in(state, data){
      state.accessToken = data
      sessionStorage.setItem("accessToken", data)
    },
    login_out(state){
      state.accessToken = null
      sessionStorage.removeItem("accessToken")
    }
  }
})

export default store

3.index.js页面

router.beforeEach((to,from,next)=>{
  // isRequireAuthTrue 
  // 是否已经登陆,验证身份
  if(sessionStorage.getItem("accessToken")){  
    next()  // 程序正常继续运行
  }else{
    if(to.path == "/login"){
      next()   // 程序正常继续运行
    }else{
      next({
        path:"/login",       // 跳转到login页面
        query:{redirect: to.path}   // 记录要进入的目标地址
      })
    }
  }
})

copy:
router.beforeEach((to,from,next)=>{})
当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。
每个守卫方法接收三个参数:

    • to: Route: 即将要进入的目标 路由对象 属性:path params query hash fullPath name meta

    • from: Route: 当前导航正要离开的路由

    • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

      • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

      • next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

      • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

      • next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

确保要调用 next 方法,否则钩子就不会被 resolved。

相关文章

网友评论

      本文标题:使用vue-router的beforeEach钩子里做登陆页面访

      本文链接:https://www.haomeiwen.com/subject/qfhowftx.html