首页 > 解决方案 > Vuex在存储中显示对象,但组件无法检索它

问题描述

我需要返回 currentGroup 对象以在 VueJS 中运行我的排行榜。

Vuex 商店按预期显示 currentGroup。但是,排行榜将商店中的 currentGroup 视为“未定义”

我尝试使用道具、数据属性和计算值来获取组,但都没有奏效。

这是我的排行榜组件:

<template>
  <div class="table-responsive mt-3">
    <table class="ui celled table" v-if="currentGroup">
      <thead>
        ...
      </thead>
      <tbody class="fixed-height-600">
        <tr v-for="(leader) in leaderboard" :key="leader.users_id">
          ...
      </tbody>
    </table>
    <MissingComponent v-else>Leaderboard</MissingComponent>
  </div>
</template>

<script>
...
export default {
  name: "Leaderboard",
  data() {
 ...
  },
  computed: {
    leaderboard () {
      return this.$store.state.reports.leaderboard;
    },
    currentGroup () {
      return this.$store.state.currentGroup;
    }
  },
  async mounted () {
    await this.$store.dispatch('getUserGroups')
    this.getLeaderboard();
  },
  methods: {
    getLeaderboard: async function () {
      console.log('in LeaderBoard, this is currentGroup: ', this.$store.state.currentGroup.name) // this returns undefined
      this.$store.dispatch("updateLeaderboard", this.currentGroup);
    },
    moment: function (datetime) {
      return moment(datetime);
    }
  }
}
</script> 

这是我的商店,应该在哪里分配:

import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
import GroupsService from '@/services/GroupsService'
import * as acts from '../store/modules/acts.js'
import * as auth from '../store/modules/auth.js'
...

// import SubscriptionsService from './services/SubscriptionsService'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    acts,
    auth,
    ...
  },
  state: {
    currentGroup: {},
    location: {},
    comment: ''
  },
  mutations: {
    setCurrentGroup(state, group) {
      console.log('seting currentGroup to: ', group) // this works correctly
      state.currentGroup = group
    },
    set_location(state, place) {
      state.location = place;
    },
    set_comment(state, comment) {
      state.comment = comment;
    }
  },
  actions: {
    getUserGroups({ commit }) {
      GroupsService.getGroups()
        .then(resp => {
          console.log('in store getUserGroups, this is usergroups: ', resp);
          console.log('setting currentGroup as resp[0]: ', resp[0]) //this is correct
            commit('setCurrentGroup', resp[0]);
        });
    }
  },
  getters: {
    currentGroup: state => {
      return state.currentGroup;
    }
  }
})

标签: vue.jsvuex

解决方案


使 getUserGroups 异步,这样await this.$store.dispatch('getUserGroups')等待结果:

async getUserGroups({ commit }) {
      const resp = await GroupsService.getGroups()
      console.log('in store getUserGroups, this is usergroups: ', resp);
      console.log('setting currentGroup as resp[0]: ', resp[0]) //this is correct
      commit('setCurrentGroup', resp[0]);
    }

推荐阅读