Arrays 如何将数组中的值更改通知VueJS/Vuex?
当我更新存储区数组中的值时,接口不会反映更改 目标:我试图显示一个简单的扫雷舰网格。单击某个单元格后,附加到该单元格的对象应将IsRevaled更新为true,表示已显示,Vuejs应将类添加到该单元格中 工作原理:IsRevaled已切换为true 工作原理:仅使用道具一切正常,但尝试学习VueJS并包括Vuex存储,UI不再随阵列更新 结构: 应用程序显示一个网格,网格显示多个单元格 用于Vuex的store.jsArrays 如何将数组中的值更改通知VueJS/Vuex?,arrays,vue.js,vuex,Arrays,Vue.js,Vuex,当我更新存储区数组中的值时,接口不会反映更改 目标:我试图显示一个简单的扫雷舰网格。单击某个单元格后,附加到该单元格的对象应将IsRevaled更新为true,表示已显示,Vuejs应将类添加到该单元格中 工作原理:IsRevaled已切换为true 工作原理:仅使用道具一切正常,但尝试学习VueJS并包括Vuex存储,UI不再随阵列更新 结构: 应用程序显示一个网格,网格显示多个单元格 用于Vuex的store.js import Vue from 'vue'; import Vuex fro
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>
在
grid.vue
中,应使用computed
和mapState
更新道具
就像:
import { mapState } from 'vuex'
// ...
<div v-for="row in gameGridAlias" class="row">
// ...
computed: mapState({
gameGridAlias: state => state.GameGrid
})
从“vuex”导入{mapState}
// ...
// ...
计算:mapState({
gameGridAlias:state=>state.GameGrid
})
更多:
*注意:mapState
是可选的,但是您可以使用它处理多个存储,而且它非常健壮,我个人在所有情况下都使用它
编辑:不要使用
this.$store.state.GameGrid[y]
或另一个this.$store.state
vars,而只使用mapState
别名以使其正常工作如何填充GameGrid我已经更新了问题以包括这部分,谢谢!!:)编辑:我应该推些什么吗?是的,有问题。我获取引用错误:未定义映射状态。
:/Edit:谢谢,我会尝试。已编辑,应为okHmmm,在访问cell.vue上的此.cell
时,我仍然无法看到可视更改:(奇怪,你确定问题来自存储吗?我正在考虑另一个解决方案。你似乎使用这个。$store
而不是mapState
别名,尝试将每个变量包装到mapState
中并使用它,我确信它会工作的
<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>
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
import { mapState } from 'vuex'
// ...
<div v-for="row in gameGridAlias" class="row">
// ...
computed: mapState({
gameGridAlias: state => state.GameGrid
})