mercredi 28 juillet 2021

create a cart that saves data with localstorage

hi i can't archive data with localstorage. I am making a shopping cart and I would like that when I change the page or reload the page I do not reset the cart, but the products inside it are kept. how can I do ? I tried to use the localstorage function but I can't figure out where to put it

my vuejs code, thanks

 data() {
  return {
    products: [
      {
        id: 1,
        name: 'Product 1',
        description: 'This is an incredibly awesome product',
        quantity: 0,
      },
      {
        id: 2,
        name: 'Product 2',
        description: 'This is an incredibly awesome product',
        quantity: 0,
      },
      {
        id: 3,
        name: 'Product 3',
        description: 'This is an incredibly awesome product',
        quantity: 0,
      }
    ],
    showCart: false
  };
},

computed: {
  cart() {
    cart = JSON.parse(localStorage.setItem('cart')); 
    return this.products.filter(product => product.quantity > 0);
  },
  totalQuantity() {
    return this.products.reduce(
      (total, product) => total + product.quantity,
      0
    );
  }
},

methods: {
  updateCart(product, updateType) {      
    for (let i = 0; i < this.products.length; i++) {
      if (this.products[i].id === product.id) {
        if (updateType === 'subtract') {
          if (this.products[i].quantity !== 0) {
            this.products[i].quantity--;
            saveCart();
          }
        } else {
          this.products[i].quantity++;
          saveCart();
        }
        break;
      }
    }
  },

  saveCart() {

    localStorage.products = JSON.stringify(products);
  }

}



Aucun commentaire:

Enregistrer un commentaire