JAVASCRIPT

Setting up and Using a Pinia Store in Vue 3

Learn how to effectively manage application state in Vue 3 by setting up a Pinia store, defining state, getters, and actions, and consuming it in components.

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

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: 'Eduardo',
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    doubleCountPlusOne() {
      return this.doubleCount + 1;
    },
  },
  actions: {
    increment() {
      this.count++;
    },
    async incrementAndFetchName() {
      // Simulate an async operation
      await new Promise(resolve => setTimeout(resolve, 500));
      this.name = 'New Name After Fetch';
      this.increment();
    },
  },
});

// src/components/CounterDisplay.vue
<template>
  <div>
    <h1>Counter: {{ counter.count }}</h1>
    <h2>Double Count: {{ counter.doubleCount }}</h2>
    <h3>Name: {{ counter.name }}</h3>
    <button @click="counter.increment()">Increment</button>
    <button @click="counter.incrementAndFetchName()">Increment & Fetch Name</button>
  </div>
</template>

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

const counter = useCounterStore();
</script>
How it works: This snippet demonstrates the basic setup and usage of a Pinia store in a Vue 3 application. It defines a `useCounterStore` with reactive `state`, `getters` for computed state, and `actions` for logic that can modify the state, including asynchronous operations. The `CounterDisplay.vue` component then consumes this store using `useCounterStore()` in the setup script, allowing direct access to state, getters, and actions for reactive updates and interactions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs