Vuex在存储中显示对象,但组件无法检索。

问题描述 投票:0回答:1

我需要返回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.js vuex
1个回答
0
投票

让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]);
    }
© www.soinside.com 2019 - 2024. All rights reserved.