当我更新商店数组中的值时,界面不会反射(reflect)更改。
目标:我正在尝试显示一个简单的扫雷网格。一旦我点击一个单元格,附加到该单元格的对象应该将 isRevealed 更新为 true 表示 is 已显示,并且 Vuejs 应该添加类 dug> 到该单元格。
有效:isRevealed 已切换为 true。
什么是有效的:仅使用 props 一切都正常,但尝试学习 VueJS 并包括 Vuex 存储 UI 不再随数组更新。
结构:
应用程序显示一个网格,网格显示多个单元格。
Vuex 的 store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
GameGrid: [],
},
mutations: {
revealCell(state, cell) {
state.GameGrid[cell.y][cell.x].isRevealed = true;
console.log("revealCell ", cell);
},
});
GameGrid 包含以下内容: 10 个包含 10 个对象的数组:
{
isRevealed: false,
x: 0,
y: 0
...
}
grid.vue,没什么特别的,显示每个单元格
<template>
<div class="grid">
<div v-for="row in $store.state.GameGrid" class="row">
<app-cell v-for="col in row" :cell="col"></app-cell>
</div>
</div>
</template>
cell.vue:
<template>
<div
@click="dig"
:class="{dug: cell.isRevealed, dd: cell.debug}">
<span class="text" v-html="cell.display"></span>
<span class="small">{{ cell.code }}</span>
</div>
</template>
<script>
export default {
props: {
cell: {
type: Object
},
},
data: function() {
return {
display: null,
}
},
methods: {
dig() {
this.$store.commit('revealCell', this.cell);
},
}
</script>
根据用户的回答进行编辑:
Grid.vue 文件
<template>
<div class="grid">
<div v-for="row in gameGridAlias" class="row">
<app-cell v-for="col in row" :cell="col"></app-cell>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex';
import Cell from './Cell.vue';
export default {
components: {
'app-cell': Cell,
},
data: {
gameGridAlias: []
},
methods: {
},
computed: mapState({
gameGridAlias: state => state.GameGrid
})
}
</script>
请注意,我收到 The "data"option should be a function that returns a per-instance value in componentDefinitions.
错误,因为 data
不返回函数.
我设置 isRevealed 的函数位于 cell.vue 上。我仍然没有看到任何 UI 更新(除了当我保存时?)。具有 this.cell.isRevealed = true
的单元格已通过 console.log 确认,但类没有更改。
这是我填充 GameGrid 的方式
当用户按下主页上的按钮时会调用此函数? App.vue 文件。
generateGrid() {
console.log("generateGrid");
//Generate empty play grid
for(let y = 0; y < this.$store.state.GameGridHeight; y++) {
this.$store.state.GameGrid[y] = new Array();
for(let x = 0; x < this.$store.state.GameGridWidth; x++) {
this.$store.state.GameGrid[y][x] = {
content: 'Empty',
code: 0,
isRevealed: false,
x: x,
y: y,
debug: false,
};
}
}
}, //End generateGrid
最佳答案
在 grid.vue
中,您应该使用 compulated
和 mapState
来更新 props
就像:
import { mapState } from 'vuex'
// ...
<div v-for="row in gameGridAlias" class="row">
// ...
computed: mapState({
gameGridAlias: state => state.GameGrid
})
更多:https://vuex.vuejs.org/en/state.html#the-mapstate-helper
*注意:mapState
是可选的,但您可以用它处理多个商店,而且它很强大,我个人将它用于所有情况。
编辑:不要使用 this.$store.state.GameGrid[y]
或其他 this.$store.state
变量,而仅使用 mapState
别名以使其正常工作
关于arrays - 如何通知 VueJS/Vuex 数组中的值发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47213776/