在VueJS中观察存储在Vuex中的数组

Vic*_*tor 7 javascript arrays vue.js vuex

我有一个客户列表,实际上是一个对象数组.我把它存放在Vuex中.我在我的组件中呈现列表,每行都有一个复选框.更确切地说,我使用keen-ui和复选框渲染部分看起来像:

<tr v-for="customer in customers" :class="{ selected: customer.selected }">
    <td>
      <ui-checkbox :value.sync="customer.selected"></ui-checkbox>
    </td>
    <td>{{ customer.name }}</td>
    <td>{{ customer.email }}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

因此,复选框直接更改了客户数组,这是坏的:我在Vuex中使用严格模式,它会抛出一个错误.

我想跟踪数组何时更改并调用操作以更改vuex状态:

watch: {
 'customers': {
  handler() {
    // ...
  },

  deep: true
}
Run Code Online (Sandbox Code Playgroud)

但是它仍然直接改变了客户.我怎样才能解决这个问题?

小智 2

首先,使用时要小心.sync:它将在 2.0 中被弃用。

看看这个: http: //vuex.vuejs.org/en/forms.html,因为这个问题在这里得到了解决。基本上,此复选框应该触发或vuex上的操作。摘自文档:inputchange

<input :value="message" @input="updateMessage">
Run Code Online (Sandbox Code Playgroud)

哪里updateMessage

vuex: {
  getters: {
    message: state => state.obj.message
  },
  actions: {
    updateMessage: ({ dispatch }, e) => {
      dispatch('UPDATE_MESSAGE', e.target.value)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您不想跟踪突变,您可以将该组件的状态移离vuex,以便能够v-model充分利用它。