What is pinia?
Pinia is a state management library for Vue.js applications. It serves as a store for shared state, with a simple and straightforward API. It is often used as an alternative to Vuex and provides reactive data stores that can be accessed throughout a Vue application.
What are pinia's main functionalities?
Defining a Store
This feature allows you to define a new store with a unique identifier, state, and actions. The state is reactive and can be accessed and manipulated across components.
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
}
});
Accessing Store State in Components
This code demonstrates how to access and use the store state within a Vue component. The store's reactive state is used in the template, and actions can be called to update the state.
<template>
<div>{{ counterStore.count }}</div>
<button @click="counterStore.increment">Increment</button>
</template>
<script setup>
import { useCounterStore } from './stores/counter';
const counterStore = useCounterStore();
</script>
Persisting State
Pinia allows for easy integration with other libraries, such as VueUse, to persist state between page reloads using local storage or other methods.
import { defineStore } from 'pinia';
import { useLocalStorage } from '@vueuse/core';
export const useUserStore = defineStore('user', {
state: () => ({
name: useLocalStorage('user-name', '')
})
});
Other packages similar to pinia
vuex
Vuex is the official state management library for Vue.js. It is more complex and verbose than Pinia, with a strict set of rules and patterns such as mutations for state changes. Pinia offers a simpler and more flexible API compared to Vuex.
redux
Redux is a state management library for JavaScript apps, not limited to Vue. It uses a single immutable state tree and pure reducer functions for state updates. Redux is known for its strict unidirectional data flow, which can be more complex than Pinia's more Vue-centric and straightforward approach.
mobx
MobX is a state management library that focuses on reactive programming. It uses observables to make state management simple and scalable. Unlike Pinia, which is designed specifically for Vue, MobX can be used with any framework, and it emphasizes transparent functional reactive programming (TFRP).