Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

vue-router auth验证怎么做?

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

这段代码写在router.js中,那么,auth.loggedIn()是怎么定义的?又是定义在那里?

router.beforeEach((to, from, next) => {
    // 取vuex中的state的值
  if (!store.state.auth) {
    if (to.path !== '/login') {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
});

this.axios.get('/platform/login/islogin/')
        .then((result) => {
          var result = result.data
          if (!result.code) {
            this.$store.commit('handleUserState')
            return true
          } else {
            this.$router.push('/login')
            return false
          }
        })

直接取vuex中的state值,auth值是会发起请求进行判断赋值,默认是false,那么beforeEach进行的时候,取的还是原来的值,不是请求回来赋值的值,想请求auth验证有什么其他方案?

Thanks you in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

router.beforeEach是会多次触发的,兄弟!你好好看看这个实现,在登录页用户输出账号后,这个beforeEach会触发,然后拿到的值就是请求过后的值,Ajax操作放在登录页做


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...