← Back to all snippets
JAVASCRIPT

Implementing Global State Management with Pinia in Vue 3

Discover how to set up and use Pinia for efficient global state management in your Vue 3 applications, defining stores with state, getters, and actions.

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

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: 'Vue 3 User',
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    fullName: (state) => `${state.name} has ${state.count} items`,
  },
  actions: {
    increment(amount = 1) {
      this.count += amount;
    },
    decrement(amount = 1) {
      this.count -= amount;
    },
    // You can also use async actions
    async incrementAsync() {
      await new Promise(resolve => setTimeout(resolve, 1000));
      this.increment(5);
    },
  },
});

// src/App.vue
<template>
  <div>
    <h1>Hello {{ counterStore.name }}!</h1>
    <p>Count: {{ counterStore.count }}</p>
    <p>Double Count: {{ counterStore.doubleCount }}</p>
    <p>{{ counterStore.fullName }}</p>
    <button @click="counterStore.increment()">Increment</button>
    <button @click="counterStore.increment(5)">Increment by 5</button>
    <button @click="counterStore.decrement()">Decrement</button>
    <button @click="counterStore.incrementAsync()">Increment Async (1s)</button>
  </div>
</template>

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

const counterStore = useCounterStore();
</script>
How it works: This snippet demonstrates using Pinia for global state management in Vue 3. It defines a `counter` store with reactive `state`, `getters` for derived data, and `actions` for modifying state, including asynchronous operations. In the component, `useCounterStore()` hooks into the store, allowing direct access to its state, getters, and actions, making state updates and access straightforward and centralized.

Need help integrating this into your project?

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

Hire DigitalCodeLabs