Pinia.js狀態(tài)管理器上手使用指南
前言
Pinia.js 是新一代的狀態(tài)管理器,由 Vue.js團(tuán)隊(duì)中成員所開發(fā)的,因此也被認(rèn)為是下一代的 Vuex,即 Vuex5.x,在 Vue3.0 的項(xiàng)目中使用也是備受推崇。
Pinia.js 有如下特點(diǎn):
- 完整的 typescript 的支持;
- 足夠輕量,壓縮后的體積只有1.6kb;
- 去除 mutations,只有 state,getters,actions(這是我最喜歡的一個(gè)特點(diǎn));
- actions 支持同步和異步;
- 沒有模塊嵌套,只有 store 的概念,store 之間可以自由使用,更好的代碼分割;
- 無需手動(dòng)添加 store,store 一旦創(chuàng)建便會(huì)自動(dòng)添加;
安裝
npm install pinia --save
創(chuàng)建 Store
新建 src/store 目錄并在其下面創(chuàng)建 index.ts,導(dǎo)出 store
// src/store/index.ts import { createPinia } from 'pinia' const store = createPinia() export default store
在 main.ts 中引入并使用。
// src/main.ts import { createApp } from 'vue' import App from './App.vue' import store from './store' const app = createApp(App) app.use(store)
State
定義State
在 src/store 下面創(chuàng)建一個(gè)user.ts
//src/store/user.ts import { defineStore } from 'pinia' export const useUserStore = defineStore({ id: 'user', // id必填,且需要唯一 state: () => { return { name: '張三' } } })
獲取 state
<template> <div>{{ userStore.name }}</div> </template> <script lang="ts" setup> import { useUserStore } from '@/store/user' const userStore = useUserStore() </script>
也可以結(jié)合 computed 獲取。
const name = computed(() => userStore.name)
state 也可以使用解構(gòu),但使用解構(gòu)會(huì)使其失去響應(yīng)式,這時(shí)候可以用 pinia 的 storeToRefs。
import { storeToRefs } from 'pinia' const { name } = storeToRefs(userStore)
修改 state
可以像下面這樣直接修改 state
userStore.name = '李四'
但一般不建議這么做,建議通過 actions 去修改 state,action 里可以直接通過 this 訪問。
export const useUserStore = defineStore({ id: 'user', state: () => { return { name: '張三' } }, actions: { updateName(name) { this.name = name } } })
<script lang="ts" setup> import { useUserStore } from '@/store/user' const userStore = useUserStore() userStore.updateName('李四') </script>
Getters
export const useUserStore = defineStore({ id: 'user', state: () => { return { name: '張三' } }, getters: { fullName: (state) => { return state.name + '豐' } } })
userStore.fullName // 張三豐
Actions
異步 action
action 可以像寫一個(gè)簡單的函數(shù)一樣支持 async/await 的語法,讓你愉快的應(yīng)付異步處理的場景。
export const useUserStore = defineStore({ id: 'user', actions: { async login(account, pwd) { const { data } = await api.login(account, pwd) return data } } })
action 間相互調(diào)用
action 間的相互調(diào)用,直接用 this 訪問即可。
export const useUserStore = defineStore({ id: 'user', actions: { async login(account, pwd) { const { data } = await api.login(account, pwd) this.setData(data) // 調(diào)用另一個(gè) action 的方法 return data }, setData(data) { console.log(data) } } })
在 action 里調(diào)用其他 store 里的 action 也比較簡單,引入對應(yīng)的 store 后即可訪問其內(nèi)部的方法了。
// src/store/user.ts import { useAppStore } from './app' export const useUserStore = defineStore({ id: 'user', actions: { async login(account, pwd) { const { data } = await api.login(account, pwd) const appStore = useAppStore() appStore.setData(data) // 調(diào)用 app store 里的 action 方法 return data } } })
// src/store/app.ts export const useAppStore = defineStore({ id: 'app', actions: { setData(data) { console.log(data) } } })
數(shù)據(jù)持久化
插件 pinia-plugin-persist 可以輔助實(shí)現(xiàn)數(shù)據(jù)持久化功能。
安裝
npm i pinia-plugin-persist --save
使用
// src/store/index.ts import { createPinia } from 'pinia' import piniaPluginPersist from 'pinia-plugin-persist' const store = createPinia() store.use(piniaPluginPersist) export default store
接著在對應(yīng)的 store 里開啟 persist 即可。
export const useUserStore = defineStore({ id: 'user', state: () => { return { name: '張三' } }, // 開啟數(shù)據(jù)緩存 persist: { enabled: true } })
數(shù)據(jù)默認(rèn)存在 sessionStorage 里,并且會(huì)以 store 的 id 作為 key。
自定義 key
你也可以在 strategies 里自定義 key 值,并將存放位置由 sessionStorage 改為 localStorage。
persist: { enabled: true, strategies: [ { key: 'my_user', storage: localStorage, } ] }
持久化部分 state
默認(rèn)所有 state 都會(huì)進(jìn)行緩存,你可以通過 paths 指定要持久化的字段,其他的則不會(huì)進(jìn)行持久化。
state: () => { return { name: '張三', age: 18, gender: '男' } }, persist: { enabled: true, strategies: [ { storage: localStorage, paths: ['name', 'age'] } ] }
上面我們只持久化 name 和 age,并將其改為localStorage, 而 gender 不會(huì)被持久化,如果其狀態(tài)發(fā)送更改,頁面刷新時(shí)將會(huì)丟失,重新回到初始狀態(tài),而 name 和 age 則不會(huì)。
最后
以上就是關(guān)于 Pinia.js 用法的一些介紹,Pinia.js 的內(nèi)容還遠(yuǎn)不止這些,更多內(nèi)容及使用有待大家自己探索。Pinia文檔
以上就是Pinia.js狀態(tài)管理器上手使用指南的詳細(xì)內(nèi)容,更多關(guān)于Pinia.js狀態(tài)管理器的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Element?table?上下移需求的實(shí)現(xiàn)
本文主要介紹了Element?table?上下移需求的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07基于el-tree實(shí)現(xiàn)懶加載穿梭條的示例代碼
這篇文章主要介紹了基于el-tree實(shí)現(xiàn)懶加載穿梭條的示例代碼,本文通過示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-03-03Element?UI/Plus中全局修改el-table默認(rèn)樣式的解決方案
element ui官方封裝好的el-table組件,好用是挺好用的,但不可避免的是默認(rèn)的樣式,下面這篇文章主要給大家介紹了關(guān)于Element?UI/Plus中全局修改el-table默認(rèn)樣式的解決方案,需要的朋友可以參考下2023-02-02SpringBoot實(shí)現(xiàn)全局和局部跨域的兩種方式
本文主要介紹了SpringBoot實(shí)現(xiàn)全局和局部跨域的兩種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01Vue.js實(shí)現(xiàn)點(diǎn)擊左右按鈕圖片切換
這篇文章主要為大家詳細(xì)介紹了Vue.js實(shí)現(xiàn)點(diǎn)擊左右按鈕圖片切換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07vue項(xiàng)目在打包時(shí),如何去掉所有的console.log輸出
這篇文章主要介紹了vue項(xiàng)目在打包時(shí),如何去掉所有的console.log輸出,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04vue等兩個(gè)接口都返回結(jié)果再執(zhí)行下一步的實(shí)例
這篇文章主要介紹了vue等兩個(gè)接口都返回結(jié)果再執(zhí)行下一步的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09Vue.js+express利用切片實(shí)現(xiàn)大文件斷點(diǎn)續(xù)傳
斷點(diǎn)續(xù)傳就是要從文件已經(jīng)下載的地方開始繼續(xù)下載,本文主要介紹了Vue.js+express利用切片實(shí)現(xiàn)大文件斷點(diǎn)續(xù)傳,具有一定的參考價(jià)值,感興趣的可以了解下2023-05-05