1. 什么是Pinia
Pinia 是 Vue 的專屬的最新狀態(tài)管理庫 ,是 Vuex 狀態(tài)管理工具的替代品
2. 手動添加Pinia到Vue項目
后面在實際開發(fā)項目的時候,Pinia可以在項目創(chuàng)建時自動添加,現(xiàn)在我們初次學(xué)習(xí),從零開始:
- 使用 Vite 創(chuàng)建一個空的 Vue3項目
npm init vite@latest
- 按照官方文檔安裝 pinia 到項目中
3. Pinia基礎(chǔ)使用
- 定義store
- 組件使用store
4. getters實現(xiàn)
Pinia中的 getters 直接使用 computed函數(shù) 進(jìn)行模擬, 組件中需要使用需要把 getters return出去
5. action異步實現(xiàn)
方式:異步action函數(shù)的寫法和組件中獲取異步數(shù)據(jù)的寫法完全一致
-
接口地址:http://geek.itheima.net/v1_0/channels
-
請求方式:get
-
請求參數(shù):無
需求:在Pinia中獲取頻道列表數(shù)據(jù)并把數(shù)據(jù)渲染App組件的模板中
6. storeToRefs工具函數(shù)
使用storeToRefs函數(shù)可以輔助保持?jǐn)?shù)據(jù)(state + getter)的響應(yīng)式解構(gòu)
7. Pinia的調(diào)試
Vue官方的 dev-tools 調(diào)試工具 對 Pinia直接支持,可以直接進(jìn)行調(diào)試
文章來源:http://www.zghlxwxcb.cn/news/detail-675494.html
8. Pinia持久化插件
官方文檔:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/文章來源地址http://www.zghlxwxcb.cn/news/detail-675494.html
- 安裝插件 pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate
- 使用 main.js
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
})
- 其他配置,看官網(wǎng)文檔即可
到了這里,關(guān)于Vue2向Vue3過度Vue3狀態(tài)管理工具Pinia的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!