一、什么是pinia?
在 Vue3 生態中,狀態管理一直是開發者關注的核心話題。隨著 Vuex 的逐步淡出,Pinia 作為官方推薦的狀態管理庫,憑借其簡潔的 API、強大的功能和對 Vue3 特性的完美適配,成為了新時代的不二之選。今天我們就來深入探討 Pinia 的使用方法和最佳實踐。
如果用生活中的例子來解釋:
Pinia 就像一個 “共享冰箱”
想象一下,你和室友合租一套公寓,你們有一個?共享冰箱(Pinia Store)。這個冰箱的作用是:
- 存放公共物品(狀態 State):比如牛奶、水果、飲料等。
- 規定取用規則(Getters):比如 “只能在早餐時間喝牛奶”。
- 處理特殊操作(Actions):比如 “牛奶喝完后要通知所有人”。
pinia官網:Pinia | The intuitive store for Vue.js
二、怎么創建一個Pinia
1. 創建項目的時候直接選擇Pinia
2. 項目中沒有Pinia時,手動下載
①安裝Pinia
npm install pinia
②在src中創建stores
③創建ts文件作為Pinia容器
④在counter.ts中加入以下代碼
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {})
1、defineStore 是 Pinia 狀態管理庫 中的一個核心函數
2、參數說明
????????第一個參數 'counter':store 的唯一標識符(不可重復)
? ? ? ? 第二個參數 () => {}:store 的配置函數,返回 store 的狀態和方法
?⑤在main.ts中掛載Pinia
import './assets/main.css'import { createApp } from 'vue'
import { createPinia } from 'pinia' // 引入創建Pinia方法
import App from './App.vue'const app = createApp(App) app.use(createPinia()) // 掛載到app頁面app.mount('#app')
這樣就成功手動實現了Pinia的手動安轉和配置了。
三、定義第一個Pinia
1、第一個選項式Pinia示例
基礎語法:
import { defineStore } from 'pinia'// 定義并導出 Store
export const defineStore實例化對象名 = defineStore('狀態管理對象名稱', {// 狀態初始化,相當于datastate: () => ({屬性名1:屬性值1}),// 計算屬性(類似 Vue 組件中的 computed)getters: {},// 方法(類似 Vue 組件中的 methond)actions: {函數}
})
?基礎示例:
/stores/counter.ts
// 1、導入defineStore
import { defineStore } from 'pinia'
import {computed,ref} from "vue";export const useCounterStore = defineStore('counter', {state() { // 相當于組件中的datareturn {title:"選項式計數管理器",count: 25 // 狀態管理變量數據}},getters: { // 相當于組件中的computeddoubleCount: (state) => state.count * 2, // 2倍計算屬性數據doubleCountPlusOne: (state) => state.count + 10 // 加10計算屬性數據},actions: { // 相當于組件中的methodsincrement() {this.count++ // 創建函數每次點擊按鈕,count加1},decrement(){this.count-- // 創建函數每次點擊按鈕,count減1}}
})
/src/App.vue
<script setup lang="ts">
// 1、導入
import {useCounterStore} from "@/stores/counter.ts"
// 2、實例化
const counterStore = useCounterStore()
</script><template>
// 3、使用
<div class="app"><h2>標題{{counterStore.title}}</h2><p>當前計數:{{counterStore.count}}</p><p>雙倍計數:{{counterStore.doubleCount}}</p><p>計數+10:{{counterStore.doubleCountPlusOne}}</p><button @click="counterStore.increment()">點擊+1</button><button @click="counterStore.decrement()">點擊-1</button>
</div>
</template>
?運行結果:
2、第一個組合式Pinia實例
基礎語法:
import { defineStore } from 'pinia'
import { ref, computed, reactive } from 'vue'export const useStoreNameStore = defineStore('storeId', () => {// 1. State - 使用 ref 或 reactiveconst count = ref(0)const state = reactive({ name: 'example' })// 2. Getters - 使用 computedconst doubleCount = computed(() => count.value * 2)// 3. Actions - 普通函數function increment() {count.value++}// 4. 返回需要暴露的屬性和方法return {count,doubleCount,increment}
})
基礎示例:
/stores/users.ts
import {defineStore} from 'pinia'
import {computed, reactive, ref} from "vue";
export const useUserStore = defineStore('user', ()=>{let isLogin = ref(false);let username = ref('未知');let email = ref('未知');let displayName = ref('未知');let roles = reactive(['管理員','用戶','玩家','游客']);let nowRole = ref('未知');let theme = ref('白色');let language = ref('chinese');let message = ref(0);function updateLoginStatus(){if(isLogin.value){isLogin.value = !isLogin.value;username.value = "未知";displayName.value = "未知";nowRole.value = "未知";message.value = 0;email.value = "未知";}else{isLogin.value = !isLogin.value;username.value = "張三";displayName.value = "追風少年";let random:number = Math.floor(Math.random()*4);nowRole.value = roles[random];message.value = 10;email.value = "zhangsan@163.com";}}function updateUserProfile(){theme.value = theme.value === 'white' ? 'dark' : 'white';language.value = language.value === 'chinese' ? 'english' : 'chinese';}function resetUser(){username.value = "未知";displayName.value = "未知";nowRole.value = "未知";message.value = 0;roles.splice(0,roles.length);email.value = "未知";}return {isLogin,username,email,displayName,nowRole,theme,language,message,updateLoginStatus,updateUserProfile,resetUser}
})
?/src/App.vue
<script setup lang="ts">
import { useUserStore } from "@/stores/users.ts";
const userStore = useUserStore();
</script>
<template>
<div class="user-profile"><h1>用戶資料</h1><!-- 直接訪問 --><p>用戶名: {{ userStore.username }}</p><p>網名: {{ userStore.displayName }}</p><!-- 解構訪問 --><div><p>郵箱: {{userStore.email }}</p><p>登錄狀態: {{ userStore.isLogin ? '登錄':'未登錄'}}</p></div><!-- 復雜數據訪問 --><div><p>主題: {{ userStore.theme }}</p><p>語言: {{ userStore.language }}</p></div><!-- 數組數據 --><div><p>角色: {{ userStore.nowRole }}</p><p>未讀通知: {{ userStore.message}}</p></div><button @click="userStore.updateLoginStatus" >{{ userStore.isLogin ? '退出':'登錄'}}</button><button @click="userStore.updateUserProfile">更新資料</button><button @click="userStore.resetUser">重置用戶</button>
</div>
</template>
運行結果:?
?
五、綜合案例
/stores/counter.ts
import {reactive} from 'vue'
import { defineStore } from 'pinia'export const useCounterStore = defineStore('counter', () => {let products = reactive([{id: 1, // 商品IDname: "蘋果16ProMax", // 商品名稱price: 12999, // 商品價格category: "phone", // 商品類別num:123, // 商品庫存數量rating: 4.8, // 商品評分},{id: 2,name: "聯想拯救者",price: 23999,category: "laptop", // 筆記本num: 0,rating: 3.8,},{id: 3,name: "華碩天選6pro",price: 11499,category: "laptop", // 筆記本num: 15,rating: 4.9,},{id: 3,name: "iQoo平板7",price: 3499,category: "tablet", // 平板電腦num: 899,rating: 3.7,},{id: 4,name: "iPad Air",price: 8599,category: "tablet", // 平板電腦num: 899,rating: 4.1,},{id: 5,name: "小米手環7",price: 999,category: "watch", // 手表num:45,rating: 4.61,},{id: 6,name: "蘋果手表6",price: 3888,category: "watch", // 手表num:45,rating: 4.9,},{id: 6,name: "小米手機",price: 3999,category: "phone",num:425,nun: 442,rating: 4.7,},],)let avgrating = products.reduce((sum,crr) => sum+crr.rating,0) / products.lengthlet avgprice = products.reduce((sum,crr) => sum+crr.price,0) / products.lengthlet sumNum = products.reduce((sum,crr) => sum+crr.num,0)let stockNum = products.filter(item=>item.num <= 0).lengthlet categories = reactive(["phone", "laptop", "tablet", "watch"])return {products,categories,avgrating,avgprice,sumNum,stockNum}
})
/src/App.vue?
<script setup lang="ts">
import {useCounterStore} from './stores/counter.ts'
import {computed, ref} from 'vue'
const store = useCounterStore()
const products = store.products
const minPrice = ref(0)
const maxPrice = ref(0)
const filteredProducts = computed(() => {return products.filter(item => item.price >= minPrice.value && item.price <= maxPrice.value)
})
</script><template><div class="container"><h1>庫存管理系統</h1><h2>總產品數據</h2><table><tr><th>商品名</th><th>商品價格</th><th>商品庫存</th><th>商品評分</th></tr><tr v-for="(item) in products"><td>{{item.name}}</td><td>{{item.price}}</td><td>{{item.num}}</td><td>{{item.rating}}</td></tr></table><strong>產品數量:{{store.sumNum}}</strong><strong>缺貨商品數量:{{store.stockNum}}</strong><strong>平均價格:{{store.avgprice}}</strong><strong>平均評分:{{store.avgrating}}</strong><h2>分類統計</h2><div class="classify" v-for="item in store.categories"><strong>{{item}}</strong><table><tr><th>商品名</th><th>商品價格</th><th>商品庫存</th><th>商品評分</th></tr><template v-for="product in products" :key="product.id"><tr v-if="product.category === item"><td>{{ product.name }}</td><td>{{ product.price }}</td><td>{{ product.num }}</td><td>{{ product.rating }}</td></tr></template></table></div><h2>商品篩選</h2><div><label>價格區間:</label><input type="number" v-model="minPrice">---<input type="number" v-model="maxPrice"><table v-if="filteredProducts.length > 0"><tr><th>商品名</th><th>商品價格</th><th>商品庫存</th><th>商品評分</th></tr><tr v-for="item in filteredProducts" :key="item.id"><td>{{ item.name }}</td><td>{{ item.price }}</td><td>{{ item.num }}</td><td>{{ item.rating }}</td></tr></table><p v-else>暫無符合條件的商品。</p></div></div>
</template><style scoped>
.container{width:1000px;padding: 20px;border: #6e7681 1px solid;box-shadow: 2px 2px 4px #bdc1c6;margin: 0 auto;
}
h1{text-align: center;
}
table{margin: 0 auto;border: #6e7681 1px solid;width:1000px;border-collapse: collapse; /* 合并邊框 */margin-bottom: 30px;
}
strong{display: block;margin-top: 10px;
}
th,tr,td{border: #6e7681 1px solid; /* 關鍵:為單元格添加邊框 */padding: 10px; /* 添加內邊距使內容更美觀 */text-align: center;
}
</style>
運行結果: