Search code examples
javascriptarraysvue.jsshopping-cartpersist

How to send vuejs array to another component without the array data being lost when i route to that component?


Hello I am currently building a vuejs shopping cart and for every product I click, I click I push that particular item into an array of objects called cart data as can be seen below

  methods: {

    addProduct: function(product){


          this.cartdata.push({
            id: product.id,
            name: product.name,
            price: product.price,
            description: product.description


          })


    }
  }

This code is where the buttons that trigger the addProduct function occur

 <div class="card-body" v-for="(products, index) in filteredProducts">
                <div class="card card-default" >


                    <div class="card-body">
                      <h2 style="padding:0px;">{{products.name}}   R{{products.price}}  </h2>

                      <p>{{products.description}}</p>
                      <button type="submit" v-on:click="addProduct (products)" class="btn btn-danger">
                          Add to cart
                      </button>
                    </div>
                </div>

I have another component called CartComponent and would like to send this array so that I can display it there with the data persisting when i route to the CartComponent. How would I go about doing this?


Solution

  • Best way is use the Vuex. You will store data in one store and you can reuse data across your components with ease.