我正在使用 Vuetify 和 Nuxt 开发 Nuxt.js 应用程序。我的一个页面显示了一个表格,其中显示了您可以加入的游戏列表。我的目标是在列表中添加或删除游戏时自动更新此表。
因此,在我的商店中,我设置了以下状态和突变:
export const state = () => ({
games: {}
})
export const mutations = {
addGame(state, game) {
state.games[game.id] = game
},
removeGame(state, id) {
delete state.games[id]
}
}
以及将游戏对象转换为列表的这个getter,以使其可由我的组件使用:
export const getters = {
games(state) {
const games = []
for (const key in state.games) {
games.push(state.games[key])
}
return games
}
}
现在这里我们有我的组件的相关部分:
<template>
<v-data-table
:headers="headers"
:items="getGames()"
class="elevation-1"
>
<template v-slot:items="props">
<td>{{ props.item.name }}</td>
<td class="text-xs-center">
{{ props.item.players.length }}/{{ props.item.numberOfPlayers }}
</td>
<v-btn :disabled="props.item.nonJoinable" class="v-btn--left" @click="joinGame(props.item.id)">
{{ props.item.nonJoinable ? 'Already joined': 'Join' }}
</v-btn>
</template>
</v-data-table>
</template>
<script>
export default {
data() {
return {
games: [],
headers: [
{
text: 'Game name',
align: 'left',
sortable: true,
value: 'name'
},
{
text: 'Players',
align: 'center',
sortable: true,
value: 'players'
}
]
}
},
async fetch({ store, params }) {
await store.dispatch('fetchGamesList')
},
methods: {
joinGame(id) {
this.$store.dispatch('joinGame', id)
},
getGames() {
console.log(this.$store.getters.games)
this.games = this.$store.getters.games
}
}
}
</script>
我已经尝试过这种配置以及将“游戏”声明为计算属性或声明“观看”方法。在任何一种情况下,只要触发上述任何突变(存储中的数据已正确更新),我都无法看到表格自动更新。
从我的组件中获得所需行为的正确方法是什么?