【问题标题】:Watching array stored in Vuex in VueJS在 VueJS 中查看存储在 Vuex 中的数组
【发布时间】:2016-12-16 22:29:17
【问题描述】:

我有一个客户列表,它实际上是一个对象数组。我将它存储在 Vuex 中。我在我的组件中呈现列表,每一行都有一个复选框。更准确地说,我使用了敏锐的 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>

所以复选框直接更改了不好的客户数组:我在 Vuex 中使用严格模式,它会抛出一个错误。

我想跟踪数组何时发生变化并调用一个动作来改变 vuex 状态:

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

  deep: true
}

但是它仍然直接改变了客户。我该如何解决这个问题?

【问题讨论】:

    标签: javascript arrays vue.js vuex


    【解决方案1】:

    如果你的客户是root状态,你可以试试这个:

    watch: {
     '$store.state.customers'{
       handler() {
        // ...
       },
    
       deep: true
     }
    }
    

    【讨论】:

      【解决方案2】:

      你只需要制作一个自定义的 getter 和 setter:

      <template>
          <ui-checkbox :value.sync="thisCustomer"></ui-checkbox>
      </template>
      
      <script>
          //this is using vuex 2.0 syntax
          export default {
              thisCustomer: {
                  get() {
                      return this.$store.state.customer;
                  },
                  set(val) {
                      this.$store.commit('SET_CUSTOMER', val);
                      // instead of performing the mutation here,
                       // you could also use an action:
                        // this.$store.disptach('updateCustomer')
                  }
             },
         }
      </script>
      

      在您的商店中:

      import {
          SET_CUSTOMER,
      } from '../mutation-types';
      
      const state = {
          customer: null,
      };
      
      const mutations = {
          [SET_CUSTOMER](state, value) {
              state.customer = value;
          },
      }
      

      我不太确定你的商店是什么样子,但希望这能给你一些想法:)

      【讨论】:

      • 此答案未能正确解释如何将计算属性与 v-for 一起使用,这是操作在其代码中显示的语句
      【解决方案3】:

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

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

      <input :value="message" @input="updateMessage">
      

      updateMessage 在哪里:

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

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

      【讨论】:

      • 意味着 Vue 3.0 吗?
      猜你喜欢
      • 2020-08-24
      • 2018-11-10
      • 1970-01-01
      • 2017-06-09
      • 2020-11-17
      • 2020-12-08
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多