vue.js - 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;
}
}
})
解决方案
使 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]);
}
推荐阅读
- jenkins - Jenkins groovy 文件中的 File.exists() 不起作用
- forms - 如何在 Prestashop 1.6 上创建帐户时使用多个复选框
- python - 如何在 prometheus 中创建自定义指标?
- android - 如何修复此用户界面
- internet-explorer - Array.from 和 forEach 中的“箭头函数”在 IE 11 中不起作用,它在控制台中引发语法错误。如何解决?
- javascript - 如何从多个单选按钮中获取值并以动态形式打印?
- sql - 如何将现有 Blob 列上的 DEFAULT 值设置为 EMPTY_BLOB()
- javascript - 根据 id 选择多个元素以获得彼此相邻的最大组
- r - 我如何增加所需的分数并作为向量返回
- r - 尝试在 R 中构建人工神经网络,但无法扩展数据集