我将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状态设置为默认值,使其具有反应性
  • 使用 setter/getter 获取数据
  • 对ajax调用
  • 使用操作
  • 在 Action
  • 中通过提交来调用变异

    注意:
  • ajax调用需要在一个 Action 中而不是在创建中,因为我将使用多个组件中的presentation
  • 我更喜欢不需要外部Vue插件的解决方案。

  • 问题
  • 我想念什么?
  • 如何以最佳方式解决它?
  • 最佳答案

    您需要使用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.ypos.x

    为了使Vue完全了解更改是否需要使用Vue.set来设置所有尚未设置为状态的内容。因此,我还需要使用Vue.set来设置pos.ypos.x

    另请参阅另一个出色的answer below

    09-25 16:58
    查看更多