1. 什么是Pinia
Pinia 是 Vue 的專屬的最新狀態管理庫 ,是 Vuex 狀態管理工具的替代品
- 提供更加簡單的APl(去掉了mutation,Pinia 中對state數據的修改可以直接通過action,Vuex中則是通過mutation)
- 提供符合組合式風格的API(和Vue3新語法統一)
- 去掉了modules的概念,每一個store都是一個獨立的模塊
- 配合TypeScript更加友好,提供可靠的類型推斷
2. 手動添加Pinia到Vue項目
后面在實際開發項目的時候,Pinia可以在項目創建時自動添加,現在我們初次學習,從零開始:
- 使用 Vite 創建一個空的 Vue3項目
npm init vite@latest
- 安裝pinia
npm install pinia
- 使用pinia
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'const pinia = createPinia()
const app = createApp(App)app.use(pinia)
app.mount('#app')
3. Pinia基礎使用
- 定義store
- 組件使用store
定義store(state+action)store/counter.js
store/counter.js
import { defineStore } from "pinia";
import { computed, ref } from 'vue'export const useCounterStore = defineStore('counter', () => {//數據 (state)const count = ref(0)//修改數據的方法 (action)const increment = () => {count.value++}const sub = () => {count.value--}// getter,用computed實現const doubleCount = computed(() => count.value * 2 )// 以對象形式返回return { count, increment, sub, doubleCount}
})
Son1.vue
<script setup>defineOptions({name: 'Son1Index'})// 1. 導入`useCounterStore`方法import { useCounterStore } from '@/stores/counter'// 2. 執行方法得到counterStore對象const counterStore = useCounterStore()
</script><template><div>我是Son1.vue {{ counterStore.count }} <button @click="counterStore.increment">+</button></div>
</template><style></style>
4. getters實現
Pinia中的 getters 直接使用 computed函數 進行模擬, 組件中需要使用需要把 getters return出去
const count = ref(0)
//getter
const doubleCount = computed(() => count.value *2)
5. action異步實現
方式:異步action函數的寫法和組件中獲取異步數據的寫法完全一致
-
接口地址:http://geek.itheima.net/v1_0/channels
-
請求方式:get
-
請求參數:無
//異步action
const getList = async () => {const res = await axios.request<接口數據類型>({})
}
6. storeToRefs工具函數
使用storeToRefs函數可以輔助保持數據(state + getter)的響應式解構
//響應式丟失,視圖不再更新
const { count, doubleCount } = counterStore//保持數據響應式
const { count, doubleCount } = storeToRefs(counterStore)
數據的解構需要通過storeToRefs()才可以保持數據響應式,如果直接解構則是拷貝一份給解構后的數據,如果是方法的解構則直接解構即可,不需要加上storeToRefs()
7. Pinia的調試
Vue官方的 dev-tools 調試工具 對 Pinia直接支持,可以直接進行調試
8. Pinia持久化插件
官方文檔:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/
pinia持久化作用等同于localstore
- 安裝插件 pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate
- 使用 main.js
// 導入持久化插件,該插件是給pinia使用的
import persist from 'pinia-plugin-persistedstate'
...
app.use(createPinia().use(persist))
- 配置 store/counter.js
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'export const useCounterStore = defineStore('counter', () => {...return {count,doubleCount,increment}
}, {persist: true
})
-
其他配置,看官網文檔即可
如果不打算持久化整個counter,可以指定具體的屬性,
persist:{paths: ['count','doubleCount'] }