I have a navbar component that I'm rendering on App.js. I have some product cards with a quick add button on another page. I want to add a cart icon on the navbar which will increase count every time I add a product from the product card. However, since they are not parent-child or siblings, I'm unsure about how to pass the data from the product card to the navbar here. Any examples will be really helpful.
Asked
Active
Viewed 162 times
1
-
1you can use Vuex (for vue2)/Pinia (for vue3) to manage your global data, or use `$root.$emit` and `$root.$on` to communicate between unrelated components easily ([here is an example](https://stackoverflow.com/a/70315823/10519069)) – DengSihan Mar 08 '23 at 01:08
-
1@DengSihan Pinia is available for 2 as well – Estus Flask Mar 08 '23 at 06:05
2 Answers
0
Here is the playground with a custom store.
Check also the answer How to pass a reactive variable... for details.
const { createApp, ref, toRef, toRefs } = Vue;
const myStore = {
counter: ref(0),
add: function() {
this.counter++
}
}
const Basket = {
setup() {
const { counter, add } = myStore
return { counter, add }
},
template: 'counter = {{counter}} <button @click="add()">+1</button>'
}
const App = {
components: { Basket },
setup() {
const { counter, add } = myStore
return { counter, add }
}
}
const app = createApp(App)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app">
Basket: <basket></basket><br/>
App: counter = {{counter}} <button @click="add()">+1</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

Tolbxela
- 4,767
- 3
- 21
- 42
0
Here is the same solution with Pinia
const { createApp, ref } = Vue
const { createPinia, defineStore, storeToRefs } = Pinia
const useStore = defineStore('currentDocument',
{
state: () => {
return {
counter: 0
}
},
actions: {
add() { this.$state.counter++ }
}
})
const Basket = {
setup() {
const store = useStore()
const { counter } = storeToRefs(store)
return {
store,
counter
}
},
template: 'counter = {{counter}} <button @click="store.add()">+1</button>'
}
const App = {
components: { Basket },
setup() {
const store = useStore()
const { counter } = storeToRefs(store)
return {
store,
counter
}
}
}
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app">
Basket: <basket></basket><br/>
App: counter = {{counter}} <button @click="store.add()">+1</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/vue-demi@0.13.11/lib/index.iife.js"></script>
<script src="https://unpkg.com/pinia@2.0.30/dist/pinia.iife.js"></script>

Tolbxela
- 4,767
- 3
- 21
- 42