JAVASCRIPT

Efficient State Management with Pinia in Vue 3

Learn to set up and use Pinia for robust, type-safe state management in your Vue 3 applications, making data flow predictable and easy to manage.

// src/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}!`
  },
  actions: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
    reset() {
      this.count = 0;
    }
  }
});

// src/main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const app = createApp(App);
app.use(createPinia());
app.mount('#app');

// src/components/CounterDisplay.vue
<template>
  <div>
    <h1>Counter: {{ counter.count }}</h1>
    <p>Double Count: {{ counter.doubleCount }}</p>
    <p>{{ counter.greeting }}</p>
    <button @click="counter.increment()">Increment</button>
    <button @click="counter.decrement()">Decrement</button>
    <button @click="counter.reset()">Reset</button>
  </div>
</template>

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

const counter = useCounterStore();
</script>

<style scoped>
button {
  margin: 5px;
  padding: 8px 15px;
  cursor: pointer;
}
</style>
How it works: This snippet demonstrates setting up a Pinia store (`useCounterStore`) with `state`, `getters`, and `actions`. The store is initialized in `main.js` and then easily consumed within a component (`CounterDisplay.vue`) using `useCounterStore()`. This pattern centralizes application state, making it reactive and accessible across different components, leading to better maintainability and predictability compared to prop drilling.

Need help integrating this into your project?

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

Hire DigitalCodeLabs