0

i am making a product page and cart page, when i click on the Addtocart buton i want the product to be added to the cart page. Now i am wokring without a database so i just want to create an array of cart and when ever i click on the button the array is appended with that product

//this is product page
<template>
  <div class="container">
    //here i am listing the products
    <div v-for="product in products" :key="product.id">
      <div>
        <h1>{{ product.name }}</h1>
        //when i click this button i want to add the product the cart array, now to go to methods
        <button @click="Add" class="button" >Add to cart</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Product',
  data () {
    return {
      products: [
        {name: 'product1', description: 'preview text', id: '1'},
        {name: 'prduct2', description: 'preview text 2', id: '2'}
      ],
      cart: []
  },
  methods: {
    //when i click the button here i have no idea how to add the product the cart
    Add () {
      this.$set(this.cart, 'name', 'product1')
    }
  }
}
</script>

3 Answers 3

1

You can expect a param in the Add function which is the id of the product. Now you can get this id in the function and then fetch the product corresponding to this id and add it to the cart array.

Sign up to request clarification or add additional context in comments.

1 Comment

You can simply add {{cart}} anywhere in your template to see its value for testing purpost. It will change as it is reactive.
0
// Data
const data = {
  products: [
    {name: 'product1', description: 'preview text', id: '1'},
    {name: 'prduct2', description: 'preview text 2', id: '2'}
  ],
  cart: []
};

// Adding product '1' to cart
const id = '1'
data.cart.push( ...data.products.filter( item => item.id === id ) );

// Result
console.log( data );

2 Comments

Thank you! it works now, i have a litte question. i passed the cart component that lists the cart array inside the product.vue component, <cart :cart="cart"/> however i want to use this on separate page and not inside the product component page, how can i establish this ?
You have use Vuex. See this 10 minutes video: youtube.com/watch?v=LW9yIR4GoVU
0

In order to add something to the cart, you'll have to pass something that's unique for each and every product, like product id, to the Add function. And then using that information, you can append the cart list with your corresponding product. Sorry, I can't help you with the code 'cause i don't work with vue.js, but I am pretty sure the above method would help. let me know if there is a problem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.