JAVASCRIPT

Centralized State Management with Pinia Store

Learn how to implement centralized state management in Vue 3 applications using Pinia, Vue's official store library, for predictable and reactive data flow.

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

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: 'Vue User'
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    greeting: (state) => `Hello, ${state.name}! Your count is ${state.count}.`
  },
  actions: {
    increment(value = 1) {
      this.count += value;
    },
    reset() {
      this.count = 0;
    }
  }
});

// App.vue (or any component)
<template>
  <div>
    <h1>Pinia Counter</h1>
    <p>Count: {{ counterStore.count }}</p>
    <p>Double Count: {{ counterStore.doubleCount }}</p>
    <p>{{ counterStore.greeting }}</p>
    <button @click="counterStore.increment()">Increment</button>
    <button @click="counterStore.increment(5)">Increment by 5</button>
    <button @click="counterStore.reset()">Reset</button>
    <input type="text" v-model="counterStore.name" placeholder="Enter name" />
  </div>
</template>

<script setup>
import { useCounterStore } from './stores/counter';

const counterStore = useCounterStore();
</script>
How it works: This snippet demonstrates implementing global state management in a Vue 3 application using Pinia. The `defineStore` function creates a store with reactive `state`, `getters` for computed state, and `actions` for modifying state. In a component, `useCounterStore()` is called to access the store instance, allowing direct access to state, getters, and actions within the template and script. This pattern centralizes application data, making it easier to manage and debug across multiple components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs