JAVASCRIPT

Vue 3 Pinia Store for Global Counter

Learn to manage global application state in Vue 3 using Pinia, Vue's official and lightweight state management library, with a practical counter example.

// stores/counter.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  actions: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
    incrementBy(amount) {
      this.count += amount;
    },
  },
  getters: {
    doubleCount: (state) => state.count * 2,
  },
});

// App.vue (or any component)
<template>
  <div>
    <p>Count: {{ counter.count }}</p>
    <p>Double Count: {{ counter.doubleCount }}</p>
    <button @click="counter.increment()">Increment</button>
    <button @click="counter.decrement()">Decrement</button>
    <button @click="counter.incrementBy(5)">Increment by 5</button>
  </div>
</template>

<script setup>
import { useCounterStore } from './stores/counter';
import { storeToRefs } from 'pinia'; // Optional: for destructuring reactive state

const counter = useCounterStore();

// You can destructure state properties directly, but they lose reactivity
// unless wrapped with storeToRefs:
// const { count, doubleCount } = storeToRefs(counter);
// For actions, you can destructure directly:
// const { increment, decrement } = counter;

</script>
How it works: This snippet demonstrates how to set up a basic Pinia store in Vue 3 for global state management. The `defineStore` function creates a store with `state` for reactive data, `actions` for modifying state, and `getters` for derived state. In a component, `useCounterStore()` hooks into the store. State can be accessed and actions called directly from the store instance. `storeToRefs` is used to maintain reactivity when destructuring state properties from the store, ensuring template updates propagate correctly.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs