One solution to this problem is to use a global state management library like Vuex or Pinia to manage the state of the basket. When the "Add to Basket" button is clicked, it can dispatch an action to add the product to the basket state. Then, the mini-basket component can be placed outside of the productView template and listen for changes to the basket state. When the state changes, the mini-basket can update to reflect the current contents of the basket.
Here's an example using Pinia:
- Install Pinia:
npm install pinia
- Create a store for the basket:
import { defineStore } from 'pinia'
export const useBasketStore = defineStore({
id: 'basket',
state: () => ({
items: []
}),
actions: {
addToBasket(product) {
this.items.push(product)
}
}
})
- In the "Add to Basket" button click handler, dispatch the addToBasket action:
<template>
<button @click="addToBasket(product)">Add to Basket</button>
</template>
<script>
import { useBasketStore } from '@/stores/basket'
export default {
props: ['product'],
methods: {
addToBasket(product) {
useBasketStore().addToBasket(product)
}
}
}
</script>
- In the mini-basket component, use a computed property to listen for changes to the basket state:
<template>
<div>
<div v-for="item in basketItems" :key="item.id">{{ item.name }}</div>
</div>
</template>
<script>
import { useBasketStore } from '@/stores/basket'
export default {
computed: {
basketItems() {
return useBasketStore().items
}
}
}
</script>
Now, when the "Add to Basket" button is clicked, the product will be added to the basket state and the mini-basket component will update to show the current contents of the basket.