JAVASCRIPT

Basic Pinia Store for Global State Management

Learn to create a simple Pinia store in Vue 3 for managing global application state, like a counter or user data, efficiently across components.

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

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

// main.js (or wherever your app is mounted)
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const app = createApp(App);
const pinia = createPinia();

app.use(pinia);
app.mount('#app');

// SomeComponent.vue
<template>
  <div>
    <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>
    <input v-model="newName" @keyup.enter="counter.setName(newName)" placeholder="Enter new name" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useCounterStore } from '@/stores/counter'; // Adjust path as needed

const counter = useCounterStore();
const newName = ref('');
</script>
How it works: This snippet demonstrates how to set up and use a basic Pinia store in a Vue 3 application. The `defineStore` function creates a reactive store with `state` for data, `getters` for derived state, and `actions` for modifying state. The store is then integrated into the Vue app using `app.use(pinia)`. Components can easily access and manipulate the store's state using the `useCounterStore()` hook within the `<script setup>` block, making global state management straightforward.

Need help integrating this into your project?

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

Hire DigitalCodeLabs