JAVASCRIPT

Vue 3 Pinia Store for Global State Management

Learn to manage global application state in Vue 3 using Pinia, Vue's official state management library. Create stores, define state, getters, and actions for 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}!`
  },
  actions: {
    increment(amount = 1) {
      this.count += amount;
    },
    reset() {
      this.count = 0;
      this.name = 'Vue User';
    }
  }
});

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

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

const counter = useCounterStore();
</script>
How it works: This snippet demonstrates how to create and use a Pinia store in Vue 3 for centralized state management. The `defineStore` function sets up your state, getters (computed properties for the store), and actions (methods for modifying state). Components can then access and modify this shared state reactively by importing and calling the `useCounterStore()` hook, making state management predictable and scalable.

Need help integrating this into your project?

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

Hire DigitalCodeLabs