Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sam's avatar
Level 4

Showing a basket outside or template

Hi folks,

So I have a bit of a project im working on which involves developing a e-commerce like functionality.

I have designed and implemented a 'slide in' mini-basket. I then have a productView template inside a 'Site' layout.

Within the productView template is a Add to Basket button, how can I get the basket to trigger and open from this button - would I need to use something like Pinia to achieve this?

0 likes
3 replies
LaryAI's avatar
Level 58

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:

  1. Install Pinia:
npm install pinia
  1. 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)
    }
  }
})
  1. 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>
  1. 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.

Sam's avatar
Level 4

@martinbean sorry thoughts I'd mentioned that. It's built in inertia.js / vue

Please or to participate in this conversation.