Vue.js & Composition API (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What is Pinia and why did it replace Vuex?
senior LevelCode ExampleState ManagementSystem DesignVue & Nuxt
In Simple Words: Pinia is the official state management library for Vue 3:
- No Mutations: In Vuex, modifying state required writing verbose
mutationsandactions. In Pinia, you modify state directly (store.count++) or call actions. - First-Class TypeScript: 100% type-safe autocomplete without magic strings or complex generic wrappers.
- Modular by Design: No nested module hell; you define independent stores (
useUserStore,useCartStore) and import them on demand. - Setup Stores: Can write stores using the exact same Composition API syntax:
typescript
export const useCartStore = defineStore('cart', () => { const items = ref<Item[]>([]); const total = computed(() => items.value.reduce((s, i) => s + i.price, 0)); function addItem(item: Item) { items.value.push(item); } return { items, total, addItem }; });