JAVASCRIPT

Vue 3 Pinia State Management for Global Data

Learn to set up and use Pinia for Vue 3 state management. This snippet demonstrates creating a store, accessing state, and modifying it across components.

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

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: 'Vue Dev'
  }),
  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/App.vue (or any component)
<template>
  <div>
    <h1>Counter App</h1>
    <p>Count: {{ counter.count }}</p>
    <p>Double Count: {{ counter.doubleCount }}</p>
    <p>{{ counter.greeting }}</p>
    <button @click="counter.increment()">Increment</button>
    <button @click="counter.incrementBy(5)">Increment by 5</button>
  </div>
</template>

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

const counter = useCounterStore();
</script>
How it works: This snippet illustrates how to create and utilize a Pinia store in a Vue 3 application. It defines a `counter` store with state, getters for derived state, and actions for modifying the state. Components can easily import and use the store to access reactive data and call actions, providing a centralized and efficient way to manage global application state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs