Pinia是Vue 3官方推薦的狀態管理模式,由尤雨溪創建并集成到了 Vue.js 中,它是一個輕量級、純粹基于函數的思想實現的應用狀態管理庫。Pinia的設計理念類似于Redux,但它更簡單易用,更適合于小型到中型的單文件組件應用。
在Vue 3項目中使用Pinia,主要有以下幾個步驟:
1. 安裝:通過npm或yarn安裝`pinia`庫:
npm install pinia vue
2. 創建store:在項目中創建一個名為store.js的文件,聲明store實例并定義state、getters、actions和mutations:
? ?```javascript
?
?import { createStore } from 'pinia';export const store = createStore({state() {// 定義初始狀態return {count: 0,};},getters: {getCount(state) {return state.count;}},actions: {increment(context) {context.commit('increment');}},mutations: {increment(state) {state.count++;}}});
? ?```
3. 使用store:在需要的地方注入store,并訪問其中的數據:
? ?```html
?
?<script setup>import { useStore } from '@pinia/core';const store = useStore();function handleClick() {store.increment();}</script><button @click="handleClick">Increment</button><p>{{ store.getCount() }}</p>
? ?```
4. 提供插件支持:Pinia可以方便地與其他Vue插件配合使用,如Vuex Router Integration等。
pinia文檔