State Management (Pinia Basics)

💚 Vue.js Lesson 15 Advanced

Pinia is the official, modern state management library for Vue.js. It allows you to share state properties across components globally in a clean, developer-friendly way.

1 Pinia stores properties

Pinia stores are organized around three key concepts, mirroring Vue components:

  • state: A function that defines the global reactive variables.
  • getters: Functions that return computed properties based on store state (automatically cached).
  • actions: Methods that contain business logic or fetch API data, mutating the state directly.
  • DevTools: Integrates seamlessly with Vue DevTools, providing detailed state tracking and time-travel debugging.
2 Creating a Pinia Store

Let's check how to declare and consume a Pinia store:

TypeScript — Pinia Store
import { defineStore } from 'pinia';

export const useCartStore = defineStore('cart', {
  // 1. Reactive state variables
  state: () => ({
    itemsCount: 0
  }),
  // 2. Computed getters
  getters: {
    isCartEmpty: (state) => state.itemsCount === 0
  },
  // 3. Methods/Actions
  actions: {
    addItem() {
      this.itemsCount++;
    },
    clearCart() {
      this.itemsCount = 0;
    }
  }
});

Import and consume the store directly in any component:

Vue — Consuming Store
<template>
  <div class="cart-details">
    <p>Cart Items: {{ cart.itemsCount }}</p>
    <button @click="cart.addItem">Add Item</button>
  </div>
</template>

<script setup>
import { useCartStore } from './stores/cart';
const cart = useCartStore();
</script>
3 Code Challenge
Challenge: Write a new Pinia store called useThemeStore that tracks a boolean flag isDarkMode, exposing an action method that toggles this flag value.