我将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并返回一个promise。我也犯了一个突变。
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 setter/getter :
getters: {
presentation: (state) => (pos) => {
return state.table.data[pos.y][pos.x].presentation;
}
},
我已经确定以下内容:
table.data
状态设置为默认值,使其具有反应性注意:
presentation
。 问题
最佳答案
您需要使用Vue.set
而不是state.table.data[pos.y][pos.x].presentation = value;
有关详细信息,请参见https://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,(我的原始海报),来自我一个词:
第一次失败的原因是,我只用
{ presentation: value }
设置了最后一部分Vue.set
,因为在另一个ajax调用中已经设置了pos.y
和pos.x
。为了使Vue完全了解更改是否需要使用
Vue.set
来设置所有尚未设置为状态的内容。因此,我还需要使用Vue.set
来设置pos.y
和pos.x
。另请参阅另一个出色的answer below。