Vue.js Lesson 10: Pinia — State Management
Pinia is the official Vue state management library (replaced Vuex). It’s simpler, TypeScript-friendly, and Vue devtools support is excellent.
Create a Store
// src/stores/user.js
import { defineStore } from "pinia";
import { ref, computed } from "vue";
export const useUserStore = defineStore("user", () => {
// State
const user = ref(null);
const isLoggedIn = computed(() => user.value !== null);
// Actions
async function login(email, password) {
const data = await authAPI.login(email, password);
user.value = data.user;
localStorage.setItem("token", data.token);
}
function logout() {
user.value = null;
localStorage.removeItem("token");
}
return { user, isLoggedIn, login, logout };
});
Use in Components
<script setup>
import { useUserStore } from "@/stores/user";
import { useCartStore } from "@/stores/cart";
// Access from ANY component — no prop drilling!
const userStore = useUserStore();
const cartStore = useCartStore();
// Reactive — template updates when store changes
</script>
<template>
<div v-if="userStore.isLoggedIn">
Welcome, {{ userStore.user.name }}!
<span>Cart: {{ cartStore.itemCount }} items</span>
</div>
</template>
You completed the Vue.js course!
- Nuxt.js — SSR framework for Vue (like Next.js for React)
- Vue Query — Data fetching for Vue
🏋️ Practice Task
Build a shopping cart with Pinia. Create cartStore: state (items array), getters (total, itemCount, isEmpty), actions (addItem, removeItem, updateQty, clearCart). Use the store in ProductList (add to cart) and CartSidebar (show items + total).
💡 Hint: defineStore(“cart”, () => { const items = ref([]); const total = computed(…); function addItem(product) {…} return {…} })