如何在vue-router的beforeEach钩子里做页面访问权限验证

一般前端做的话放到sessionStorage里面,通过vuex去管理,直接上代码吧(我项目里'/'是登录页,'/Table'是登录后的首页)

// main.js
router.beforeEach((to, from, next) => {
  if (to.path === '/' && sessionStorage.getItem('accessToken') && from.path !== '/Table'){
    sessionStorage.removeItem('accessToken')
    next()
  }
  else if (to.meta.requiresAuth && !sessionStorage.getItem('accessToken')){
    next(
      {
        path: '/',
        query: {redirect: to.fullPath}
      }
    )
  }
  else if (from.path === '/Table' && to.path === '/'){
    next({
      path: '/Table'
    })
  }
  else{
    next()
  }
})

下面是登录页

  login (){
    var _this = this;
    let params = {}
    params = {
      username: this.username,
      password: this.password
    }
    api.login_in(params).then(data => {
      if (data) {
        this.$store.commit(types.LOGIN_IN, data)
        this.$router.push(this.$route.query.redirect || '/Table');
        Toast({
          message: '登录成功',
          iconClass: 'icon-success',
        })
      }
    })     
  }

然后是store.js

const state = {
  accessToken: null
}

const mutations = {
  [types.LOGIN_IN] (state, data) {
    state.accessToken = data
    sessionStorage.setItem('accessToken', JSON.stringify(data.name))
  },
  [types.LOGIN_OUT] (state, data) {
    state.accessToken = null
  }
}

猜你喜欢

转载自blog.csdn.net/znysys520/article/details/80358360
今日推荐