Home > Mobile >  How to push an object to an array of object using Vue 3?
How to push an object to an array of object using Vue 3?

Time:11-02

I am trying to push an object to a list of objects in vuetify. Im using Vue 3.

This is my html code:

  <a to="#" data-toggle="tooltip" data-placement="top" title="Add to cart"
    @click.stop.prevent="handleAddToCart(product)">
   <v-icon >mdi-medical-bag</v-icon>
  </a>

Note: I have used stop.prevent cause the icon is inside a div which is clickable.

This is what I have tried in my click event method: declared in data: productList = []

       handleAddToCart(product) {
        this.productList.push(product)
        console.log('product list', this.productList)
        this.$cookies.set('cart', JSON.stringify(this.productList))
      }

I want to save this array in cookies but it keeps replacing object and not pushing the object one after another.

enter image description here

CodePudding user response:

  data() {
    return {
      productList : []
    }
  }
...
       handleAddToCart(product) {
        this.productList.push(product)
        console.log('product list', productList)
        this.$cookies.set('cart', JSON.stringify(productList))
      }

CodePudding user response:

That happens because each time you click create a new array let productList = [], you need to keep your array reference in the data attribute.

export default {
  data: {
    return {
       productList: []
    }
  },
  methods: {
    handleAddToCart(product) {
        this.productList = [...this.productList, product]
        console.log('product list', this.productList)
        this.$cookies.set('cart', JSON.stringify(this.productList))
    }

  }
}

CodePudding user response:

Looks like your productList is a proxy object, You can get the target array from this proxy and then push the new product in it.

You can give a try to this :

handleAddToCart(product) {
  const proxyArr = new Proxy(this.productList, {
    get(target, prop, receiver) {
      return target[prop];
    }
  });

  this.productList = [...proxyArr];
  this.productList.push(product);
  this.$cookies.set('cart', JSON.stringify(this.productList))
}
  • Related