我用Vue和Vuex。在一种情况下,我使用Ajax获取表示值。在路上的某个地方,可能在computed,它不再是反应性的了。
组件中的:
props: [ 'x', 'y' ],
template: `
<div class="presentation">
{{ presentation }}
</div>
`,
computed: {
presentation() {
return this.$store.getters.presentation({ x: this.x, y: this.y });
}
}Vuex商店:
const store = new Vuex.Store({
state: {
table: {
data: []
}
},
...Vuex动作:
我用ajax调用一个url并返回一个承诺。我也犯了突变。
actions: {
save: (context) => {
let uri = 'some/uri';
let params = {};
let value = 'A value';
return axios
.post(uri, params)
.then((response) => {
context.commit('setPresentation', value);
})
.catch((error) => {
console.log('error');
})
.finally(() => {});
},
},Vuex突变:
mutations: {
setPresentation: (state, value) => {
let pos = state.table.pos;
state.table.data[pos.y][pos.x].presentation = value;
},
}Vuex getter:
getters: {
presentation: (state) => (pos) => {
return state.table.data[pos.y][pos.x].presentation;
}
},我已经确定了以下几点:
table.data状态设置为默认值,以使其具有反应性。备注:
presentation。问题
发布于 2019-08-09 06:35:34
您需要使用Vue.set而不是state.table.data[pos.y][pos.x].presentation = value;
详细信息请参见https://v2.vuejs.org/v2/guide/list.html#Caveats
尝试用以下代码更新您的突变:
if (!state.table.data[pos.y]) {
Vue.set(state.table.data, pos.y, [])
}
Vue.set(state.table.data[pos.y], pos.x, { presentation: value })我的话,OP (原版海报):
第一次失败的原因是,我只使用Vue.set设置了最后一部分Vue.set,因为在另一个ajax调用中已经设置了pos.y和pos.x。
对于Vue来说,要完全了解是否需要使用Vue.set设置所有尚未在状态中设置的更改。所以我需要使用Vue.set来设置pos.y和pos.x。
还可以看到另一个优秀的回答如下。
当直接使用索引设置项时,Vue无法检测到对数组的更改。
发布于 2019-08-09 12:45:05
你的变异没问题,没有问题。只要Vue观察到对象,Vue就会检测到对象的presentation属性的赋值。
在大多数情况下,Vue会自动观察对象,但是有一些怪癖(特别是对于数组),您需要注意。
当直接使用索引(文档)设置项时,Vue无法检测到对数组的更改。
我假设您正在以下列方式填充数组:
for (let y = 0; y < Y_MAX; y++) {
// This is bad! Vue cannot detect this change
state.table.data[y] = []
for (let x = 0; x < X_MAX; x++) {
// Same as above, Vue cannot detect this change. As a consequence,
// the object you are assigning to the array will not be observed
// by Vue! So if you were to mutate the presentation property
// of this object, Vue won't know about it.
state.table.data[y][x] = { presentation: '...' }
}
}因此,要解决您的问题,只需确保不以下列方式更改数组:
array[index] = whatever你需要这样做:
Vue.set(array, index, whatever)或者,您可以先构建数组,然后将其分配给state.table.data;Vue将检测赋值,然后递归地观察数组及其中包含的所有内容。
const data = []
for (let y = 0; y < Y_MAX; y++) {
data[y] = []
for (let x = 0; x < X_MAX; x++) {
data[y][x] = { presentation: '...' }
}
}
// After this assignment, data (and all objects contained within it)
// will be observable
state.table.data = data发布于 2019-08-09 07:09:39
看起来你的道具是个数组。您确定这个.x和this.x .y在表示方法中返回正确的值吗?
https://stackoverflow.com/questions/57424474
复制相似问题