JAVASCRIPT

Simple Global State Management with Pinia in Vue 3

Learn to manage application-wide state effortlessly in Vue 3 using Pinia, Vue's recommended store library, with a clear counter example.

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

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

// App.vue (or any component)
<template>
  <div>
    <p>Count: {{ counterStore.count }}</p>
    <p>Double Count: {{ counterStore.doubleCount }}</p>
    <button @click="counterStore.increment()">Increment</button>
    <button @click="counterStore.decrement()">Decrement</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 for global state management in Vue 3. It defines a `counter` store with a `count` state, a `doubleCount` getter, and `increment`/`decrement` actions. Components then import and use this store, reacting to state changes and dispatching actions, providing a centralized and reactive way to manage application data efficiently.

Need help integrating this into your project?

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

Hire DigitalCodeLabs