vue+vue-router+vuex 登录表单提交之后,在beforeEach钩子里查询不到store里的内容

vue+vue-router+vuex 登录表单提交之后,在router里边的beforeEach钩子里查询store跟store.user.currentUser 结果不一样

router.js

const routes = [
  {
    path: '/',
    components: {
      default: Site,
      header: SiteHeader,
      footer: SiteFooter
    },
    children: [
      {
        path: '',
        name: 'home',
        component: Home,
        meta: {
          auth: false
        }
      }, {
        path: 'about',
        name: 'about',
        component: About,
        meta: {
          auth: false
        }
      }
    ]
  }, {
    path: '/backend',
    components: {
      default: Backend,
      header: BackendHeader,
      footer: BackendFooter
    },
    children: [
      {
        path: '',
        name: 'dashboard',
        meta: {
          auth: true
        },
        component: Dashboard
      }, {
        path: 'brand',
        name: 'brand',
        meta: {
          auth: true
        },
        component: Brand
      }
    ]
  }, {
    path: '/sign_in',
    name: 'sign_in',
    meta: {
      auth: false
    },
    component: SignIn
  }
]

const router = new Router({mode: 'history', routes: routes})

router.beforeEach((to, from, next) => {
  console.log('store.state', store.state)
  console.log('store.state.user.currentUser', store.state.user.currentUser)

  if (to.meta.auth) {
    if (store.state.user.currentUser) {
      next()
    } else {
      next({
        path: '/sign_in',
        query: {
          redirect: to.fullPath // 将跳转的路由path作为参数,登录成功后跳转到该路由
        }
      })
    }
  } else {
    if (store.state.user.currentUser && to.path === '/sign_in') {
      next({path: '/backend'})
    } else {
      next()
    }
  }
})

signIn.vue

    submitForm (formName) {
      var _this = this
      this.$refs[formName].validate((valid) => {
        _this.loading = true
        if (valid) {
          _this.signIn(_this.form).then(() => {
            _this.loading = false
            _this.$router.replace({path: '/backend'})
          })
        } else {
          _this.loading = true
          return false
        }
      })
    },

store

import {SIGN_IN} from '../types'
import api from '@/config/api'

const user = {
  namespaced: true,
  state: {
    currentUser: JSON.parse(localStorage.getItem('currentUser'))
  },
  mutations: {
    [SIGN_IN] (state, user) {
      state.currentUser = user
    }
  },
  actions: {
    async [SIGN_IN] ({commit}, data) {
      return new Promise((resolve, reject) => {
        api.user.signIn(data).then((response) => {
          const user = response.user
          localStorage.setItem('currentUser', JSON.stringify(user))
          commit(SIGN_IN, user)
        })
        resolve()
      })
    }
  },
  getters: {}
}

export default user

运行结果,点击一下按钮log打出来的结果

clipboard.png

clipboard.png

点击第二次登录后就能进入了

谁能指点一下怎么正确获取store中的值啊!


更新:
刚才又试了一下,点击第一下连localstorage的值都取不到,有人碰到过这种问题么?

clipboard.png

图片描述

阅读 4.7k
2 个回答

建议在 getters 内写获取方法,返回从 localStorage 里拿的数据。

getters: {
    currentUser: () => {
    return JSON.parse(localStorage.getItem('currentUser'))
}

伤心啊,还是闭包的缘故啊

clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题