为什么v-model会改变Vuex状态而不是componets的本地数据?

时间:2018-06-06 09:56:13

标签: vue.js vue-component vuex

我制作了我的第一个Vue项目,everthing还可以,所以我添加了Vuex(将来它不会是多余的,我为了感兴趣而尝试了),一切都还行,直到我启用严格模式。事实证明,组件变异存储在变异之外的存储状态,但是我还没有想要它并且在data()的组件中创建了一个nessesary对象的本地副本。

我的目的是在父组件中创建一个本地对象,然后将其属性传递给v-model的子组件(我知道它是v-bind的事件驱动语法糖和v-on:input)当本地对象更新时(在v-model内的子项内),父组件的方法将调度操作以进行存储。而不是它,由于外部变异我得到一个错误消息,而且它只发生在第二个和后续的输入事件。

此外,如果我在ProdutRow组件观察器中替换这些行,它也可以工作:

item: {
                handler(value) {
                    this.$store.dispatch('updateProduct', {
                        product: value,
                        index: this.index,
                    });
                },
                deep: true,
            }

使用:product: {...value},Object.assign({}, value),但商店操作中的相同代码不会:它会引发相同的错误。

data()创建指定道具的副本吗?如果是这样,为什么Object.assign不在商店工作?

代码:

store.js

    import Vue from 'vue';
    import Vuex from 'vuex';
    import {ADD_PRODUCT, UPDATE_PRODUCT, DELETE_PRODUCT, UPDATE_FORM, UPDATE_PREPAYMENT_IN_PERCENT} from './mutation-types';
    import _ from 'lodash';

    Vue.use(Vuex);

    let id = 1;
    const product = {
        order: id++,
        name: '',
        size: '',
        content: '',
        price: 0,
        number: 1,
        discount: '',
        guarantee: 0,
        promotion: 0,
        location: '',
        sum: 0,
    };
    export default new Vuex.Store({
        strict: true,
        state: {
            products: [
                Object.assign({}, product),
            ],
            form: {
                prepaymentInPercent: 100,
            }

        },
        getters: {
            total(state) {
                return state.products.reduce(function (acc, cur, index, array) {
                    return array.length > 1 ? acc + cur.sum : cur.sum;
                }, 0);
            },
            rest(state, getters) {
                return getters.total - getters.prepaymentInRub;
            },
            prepaymentInRub(state, getters) {
                return getters.total * state.form.prepaymentInPercent / 100;
            }
        },
        mutations: {
            [ADD_PRODUCT](state, product) {
                state.products.push(product);
            },
            [UPDATE_PRODUCT](state, {product, index}) {
                state.products.splice(index, 1, product);
            },
            [DELETE_PRODUCT](state, index) {
                state.products.splice(index, 1);
            },
            [UPDATE_FORM](state, form) {
                state.form = form;
            },
            [UPDATE_PREPAYMENT_IN_PERCENT](state, percent) {
                state.form.prepaymentInPercent = percent;
            }

        },
        actions: {
            addProduct({commit}) {
                let newProduct = Object.assign({}, product);
                newProduct.order = id++;
                commit(ADD_PRODUCT, newProduct);
            },
            updateProduct: _.debounce(function ({commit}, product) {
                commit(UPDATE_PRODUCT, product);
            }, 1),
            deleteProduct({commit, state}, index) {
                state.products.length > 1 && commit(DELETE_PRODUCT, index)
            },
            updatePrepaymentInPercentByRub({commit, getters}, rubles) {
                let percent = Math.round(rubles / getters.total * 100);
                commit(UPDATE_PREPAYMENT_IN_PERCENT, percent);
            }
        },
    });

ProductTable.vue

    <template>
      <table border="0">
        <thead>
        <tr>
          <th class="pointer" @click="addProduct">+</th>
          <th>Номер</th>
          <th>Название</th>
          <th>Размер</th>
          <th>Наполнение</th>
          <th>Цена</th>
          <th>Количество</th>
          <th>Скидка</th>
          <th>Акция</th>
          <th>Сумма</th>
          <th>Гарантия</th>
          <th>Заказ</th>
          <th class="pointer" @click="toJSON">JSON</th>
        </tr>
        </thead>
        <tbody>
        <template v-for="(product, index) in products">
          <ProductRow
                  :initialItem="product"
                  :key="product.order"
                  :index="index"
          />
        </template>
        <tr>
          <td colspan="12">{{total}}</td>
          <td>{{json}}</td>
        </tr>
        </tbody>
      </table>
    </template>

    <script>
      import ProductRow from './ProductRow';
      import {mapGetters, mapActions, mapState} from 'vuex';

      export default {
        components: {
          ProductRow,
        },
        name: 'ProductTable',
        data() {
          return {
            json: '',
          };
        },
        computed: {
          ...mapState(['products']),
          ...mapGetters(['total']),
        },
        methods: {
          ...mapActions(['addProduct']),
          toJSON() {
            this.json = JSON.stringify({
              products: this.products,
              total: this.total,
            }, null, '\t');
          },
        },
      };
    </script>

ProductRow

<template>
    <tr>
        <td colspan="2" class="id">{{indexFrom1}}</td>
        <Editable v-model="item.name"/>
        <Editable v-model="item.size"/>
        <Editable v-model="item.content"/>
        <Editable v-model.number="item.price"/>
        <Editable v-model.number="item.number"/>
        <Editable v-model="item.discount"/>
        <td>
            <select v-model="item.promotion">
                <option selected="" value="0">Нет</option>
                <optgroup label="Новоселы">
                    <option data-text="Нов." value="5">Новоселы -5%</option>
                    <option data-text="Нов." value="10">Новоселы -10%</option>
                    <option data-text="Нов." value="15">Новоселы -15%</option>
                </optgroup>
            </select>
        </td>
        <td>{{sum}}</td>
        <Editable v-model.number="item.guarantee"/>
        <td>
            <select v-model="item.location">
                <option selected value="">Услуги</option>
                <option value="СКЛАД">Склад</option>
                <option value="ЗАКАЗ">Заказ</option>
            </select>
        </td>
        <td>
            <span class="table-remove" @click="removeProduct(index)">Удалить</span>
        </td>
    </tr>
</template>

<script>
    import Editable from './EditableCell';

    export default {
        components: {
            Editable,
        },
        name: 'ProductRow',
        props: {`enter code here`
            initialItem: Object,
            index: Number,
        },
        data() {
            return {
            item: this.initialItem
        };

        },
        computed: {
            sum() {
                let prod = this.item.price * this.item.number;
                let discounted = this.isDiscountInPercent(this.item.discount) ?
                    prod * this.getCoeffFromPercent(this.item.discount) :
                    prod - this.item.discount;
                let result = Math.round(discounted * this.getCoeffFromPercent(this.item.promotion));
                return result > 0 ? result : 0;
            },
            indexFrom1() {
                return this.index + 1;
            },
        },
        methods: {
            getCoeffFromPercent(percent) {
                return 1 - parseInt(percent) / 100;
            },
            isDiscountInPercent(discount) {
                return ~discount.indexOf('%') ? true : false;
            },
            removeProduct(index) {
                // console.log(arguments);
                this.$store.dispatch('deleteProduct', index)

            }
        },
        watch: {
            sum() {
                this.item.sum = this.sum;
            },
            item: {
                handler(value) {
                    this.$store.dispatch('updateProduct', {
                        product: value,
                        index: this.index,
                    });
                },
                deep: true,

            },
        },
    };
</script>

1 个答案:

答案 0 :(得分:1)

不,data()不会创建项目对象的副本,因此在此代码中,您将通过引用传递对象。

data() {
   return {
        item: this.initialItem
    };
}

这意味着商店中的产品对象与ProductRow组件中的this.item完全相同。因此,当您在输入中附加v-model时,您将直接更改商店中的产品对象。

使用商店中的Object.assign()克隆产品对象将无效。您必须在ProductRow组件中进行克隆。

data() {
   return {
      item: Object.assign({}, this.initialItem)
   };
}

这将创建一个副本,这样您就不会直接修改商店中的产品。