JAVASCRIPT

Basic Pinia Store Setup and Usage for State Management

Learn to set up a basic Pinia store in Vue 3 for centralized state management, defining state, getters, and actions, and consuming it in components.

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

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: 'My Awesome Counter'
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    greeting: (state) => `Hello from ${state.name}!`
  },
  actions: {
    increment(amount = 1) {
      this.count += amount;
    },
    decrement(amount = 1) {
      this.count -= amount;
    },
    reset() {
      this.count = 0;
    }
  }
});


// main.js (Integration with Pinia)
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

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

app.use(pinia); // Make sure to use Pinia
app.mount('#app');


// App.vue (Example Usage)
<template>
  <div>
    <h1>{{ counter.greeting }}</h1>
    <p>Count: {{ counter.count }}</p>
    <p>Double Count: {{ counter.doubleCount }}</p>

    <button @click="counter.increment()">Increment</button>
    <button @click="counter.decrement(2)">Decrement by 2</button>
    <button @click="counter.increment(5)">Increment by 5</button>
    <button @click="counter.reset()">Reset</button>
  </div>
</template>

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

const counter = useCounterStore();
</script>
How it works: This snippet demonstrates the fundamental setup and usage of a Pinia store in a Vue 3 application. It defines a `counter` store with reactive `state`, `getters` for derived state, and `actions` for modifying the state. The store is initialized in `main.js` using `createPinia()` and `app.use(pinia)`, and then easily consumed within any component using the `useCounterStore()` hook, providing a clean 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