← Back to all snippets
JAVASCRIPT

Vue 3 Pinia Store Setup and Usage for State Management

Learn how to set up a Pinia store in a Vue 3 application for robust state management, including defining state, getters, and actions, and using them in components.

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

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

// src/components/CounterComponent.vue
<template>
  <div>
    <h1>Count: {{ counterStore.count }}</h1>
    <h2>Double Count: {{ counterStore.doubleCount }}</h2>
    <p>{{ counterStore.greeting }}</p>
    <button @click="counterStore.increment()">Increment</button>
    <button @click="counterStore.incrementBy(5)">Increment by 5</button>
  </div>
</template>

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

const counterStore = useCounterStore();
</script>
How it works: This snippet demonstrates setting up a basic Pinia store (`counter.js`) with state, getters, and actions. It then shows how to import and use this store within a Vue 3 component (`CounterComponent.vue`) using the Composition API, accessing state, getters, and dispatching actions. Pinia is the recommended state management library for Vue 3, offering a simpler and more performant alternative to Vuex.

Need help integrating this into your project?

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

Hire DigitalCodeLabs