Vuex 状态未返回正确的状态值

时间:2021-07-14 02:33:45

标签: javascript vue.js vuex vue-router

我尝试console.log isAuthenticated getter 状态及其返回的 false 即使在开发工具 Vuex 选项卡中状态值为 true

下面是store.js

import axios from 'axios'

export default {
  namespaced: true,
  state: {
    bearerToken: null,
    userData: null,
  },
  getters: {
    isAuthenticated(state) {
      if (state.bearerToken && state.userData) {
        return true
      }
      return false
    },
    userData(state) {
      return state.userData
    },
  },
  actions: {
    async login({ dispatch }, credentials) {
      const response = await axios({
        url: 'api/auth/login',
        data: credentials,
        method: 'POST',
      })
      dispatch('attempt', response.data.bearerToken)
    },
    async attempt({ commit, state }, bearerToken) {
      if (bearerToken) {
        commit('SET_BEARER_TOKEN', bearerToken)
      }

      // ? If bearerToken is null or invalid stop here
      if (!state.bearerToken) {
        return
      }
      
      // ? If bearerToken is valid get user data
      try {
        const response = await axios({
          url: 'api/auth/me',
          method: 'GET',
        })
        commit('SET_USER_DATA', response.data)
      } catch (error) {
        commit('SET_BEARER_TOKEN', null)
        commit('SET_USER_DATA', null)
      } 
    },
    logout({ commit }) {
      return axios({
        url: 'api/auth/logout',
        method: 'POST',
      })
        .then(() => {
          commit('SET_BEARER_TOKEN', null)
          commit('SET_USER_DATA', null)
        })
    },
  },
  mutations: {
    SET_BEARER_TOKEN(state, bearerToken) {
      state.bearerToken = bearerToken
    },
    SET_USER_DATA(state, userData) {
      state.userData = userData
    },
  },
}

下面是router.js

import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const ifNotAuthenticated = (to, from, next) => {
  console.log(store.getters['authentication/isAuthenticated']) // <- this returns false
  console.log(store.getters.isAuthenticated) // <- this returns undefined
  if (!store.getters['authentication/isAuthenticated']) {
    next()
    return
  }
  next({ name: 'dashboard' })
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior() {
    return { x: 0, y: 0 }
  },
  routes: [
    {
      path: '/',
      name: 'dashboard',
      component: () => import('@/views/Dashboard.vue'),
      meta: {
        pageTitle: 'Dashboard',
        breadcrumb: [
          {
            text: 'Dashboard',
            active: true,
          },
        ],
      },
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
      beforeEnter: ifNotAuthenticated,
      meta: {
        layout: 'full',
      },
    },
    {
      path: '/error-404',
      name: 'error-404',
      component: () => import('@/views/error/Error404.vue'),
      meta: {
        layout: 'full',
      },
    },
    {
      path: '*',
      redirect: 'error-404',
    },
  ],
})

// ? For splash screen
// Remove afterEach hook if you are not using splash screen
router.afterEach(() => {
  // Remove initial loading
  const appLoading = document.getElementById('loading-bg')
  if (appLoading) {
    appLoading.style.display = 'none'
  }
})

export default router

0 个答案:

没有答案