0

I'm creating a shopping cart in VueJS. I have the cart icon in the header and my products in another component. I need to take the array of products inside of the header so i can print the length near to the cart icon. Here some code:

data: () => {
    return {
        cart: [],
        products: [
            {
                name: "Margherita",
                price: 5,
                image: "https://www.scattidigusto.it/wp-content/uploads/2018/03/pizza-margherita-originale-Scatti-di-Gusto-1568x821.jpg"
            },
            {
                name: "Marinara",
                price: 4,
                image: "https://wips.plug.it/cips/buonissimo.org/cms/2012/05/pizza-marinara-5.jpg"
            },
            {
                name: "Diavola",
                price: 6,
                image: "https://www.coopshop.it/p/wp-content/uploads/2021/02/Salame_940x450.jpg"
            }
        ]
    }
CodingCalf
  • 21
  • 2
  • Does this answer your question? [Communication between sibling components in Vue.js 2.0](https://stackoverflow.com/questions/38616167/communication-between-sibling-components-in-vue-js-2-0) – kissu Apr 19 '22 at 15:42
  • You could either use [`this.$emit(...)`](https://v2.vuejs.org/v2/guide/components-custom-events.html) to pass the data up to the parent, then back down the the sibling child using props. But a much better approach would be to use a Store (like [VueX](https://vuex.vuejs.org/)) to easily share data between components at any level – Alicia Sykes Apr 19 '22 at 15:42

1 Answers1

0

You should store the list of products inside your Vuex store. From there the list will be available to each and every component in your application.

IVO GELOV
  • 13,496
  • 1
  • 17
  • 26
  • Vuex should not be a default. Understand how parent/child relationship works is more important actually. – kissu Apr 19 '22 at 15:44
  • 1
    The OP does not have a direct parent/child relationship - his Header component may be nested 2 levels away from the Root while his current `` content might also have nested children. So learning why a shared store is needed in non-trivial applications is also important. – IVO GELOV Apr 19 '22 at 15:48