How do I push items into an array in the data object in Vuejs? Vue seems not to be watching the .push() method

我的未来我决定 提交于 2019-12-05 11:06:22

The push() method ought to add purchase objects to the queue array, but as @FK82 pointed out in his comment, push() is adding multiple references to the same purchase object. This means that if you change the object by increasing the quantity, every purchase's quantity property will be updated.

You can give that a try here:

const exampleComponent = Vue.component("example-component", {
  name: "exampleComponent",
  template: "#example-component",
  data() {
    return {
      queue: [],
      purchase: {
        product: null,
        customer: null,
        quantity: null
      }
    };
  },
  methods: {
    queuePurchase() {
      this.queue.push( this.purchase );
    }
  }
});

const page = new Vue({
  name: "page",
  el: ".page",
  components: {
    "example-component": exampleComponent
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<template id="example-component">
  <div>
    <p>The Queue has {{ this.queue.length }} items.</p>
    <input
      v-model="purchase.quantity"
      type="number"
      min="1"
      name="product"
      placeholder="Quantity"
    >
    <button @click="queuePurchase">
      Add to Queue
    </button>
    <pre>{{ JSON.stringify(this.queue, null, 2) }}</pre>
  </div>
</template>

<div class="page">
  <example-component></example-component>
</div>

Instead of push()ing a reference to the same purchase object, try creating a shallow copy with Object.assign({}, this.purchase) or by using the spread operator. Here's an example that uses the spread operator and then push()es the copy onto the queue:

const exampleComponent = Vue.component("example-component", {
  name: "exampleComponent",
  template: "#example-component",
  data() {
    return {
      queue: [],
      purchase: {
        product: null,
        customer: null,
        quantity: null
      }
    };
  },
  methods: {
    queuePurchase() {
      this.queue.push({...this.purchase});
    }
  }
});

const page = new Vue({
  name: "page",
  el: ".page",
  components: {
    "example-component": exampleComponent
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<template id="example-component">
  <div>
    <p>The Queue has {{ this.queue.length }} items.</p>
    <input
      v-model="purchase.quantity"
      type="number"
      min="1"
      name="product"
      placeholder="Quantity"
    >
    <button @click="queuePurchase">
      Add to Queue
    </button>
    <pre>{{ JSON.stringify(this.queue, null, 2) }}</pre>
  </div>
</template>

<div class="page">
  <example-component></example-component>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!