vue3如何用pinia替代vuex
pinia是vue團(tuán)隊(duì)推薦代替vuex的一款輕量級(jí)狀態(tài)管理庫(kù)。
1. 安裝
npm i pinia --save
2. pinia特點(diǎn)
- 完整的typescript支持
- 足夠輕量,壓縮后的體積只有1.6kb
- 去除mutations,只保留state,getters,actions
- actions同時(shí)支持同步和異步
- 沒有modules模塊的概念,只有store,store之間可以互相引用,更好的代碼分割
3. 使用
1.初始化store
創(chuàng)建目錄store/index.ts
import { createPinia } from 'pinia'
const store = createPinia()
export default store
2.在main.ts引用store
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
const app = createApp(App)
app.use(store)
app.mount('#app')
3.創(chuàng)建store
根據(jù)功能模塊在store下創(chuàng)建ts文件,維護(hù)各個(gè)功能的數(shù)據(jù),如用戶模塊user.ts,維護(hù)兩個(gè)字段:userInfo和token,通過actions里面的方法修改userInfo和token的內(nèi)容
import { defineStore } from 'pinia'
interface UserInfo {
name?: string
age?: number
}
// 第一個(gè)參數(shù)是id,id必填,且需要保證值唯一
export const useUserStore = defineStore('user', {
state: (): {
userInfo: UserInfo
token: string
} => {
return {
userInfo: {},
token: ''
}
},
getters: {
newName: state => state.userInfo.name + '牛'
},
actions: {
updateUserInfo(userInfo: UserInfo) {
this.userInfo = userInfo
},
updateToken(token: string) {
this.token = token
}
}
})
4.讀取數(shù)據(jù)
引入要讀取的store
<script setup lang="ts">
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
// 讀取state中的數(shù)據(jù)
const userInfo: ComputedRef<{
name?: string
age?: number
}> = computed(() => userStore.userInfo)
// 讀取getter中的數(shù)據(jù)
const newName = userStore.newName
</script>
5.修改數(shù)據(jù)
<script lang="ts" setup>
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
function handleLogin() {
userStore.updateUserInfo({ name: '李二' })
}
</script>
6.store的相互引用
不同store之間引用,舉個(gè)??:創(chuàng)建user2.ts,引用user.ts的數(shù)據(jù)
import { defineStore } from 'pinia'
import { useUserStore } from './user'
export const useUser2Store = defineStore('user2', {
state: (): {
sex: string
} => {
return {
sex: '0'
}
},
actions: {
sayInfo(sex: string) {
this.sex = sex
// 引用其他store
const userStore = useUserStore()
console.log(
`我叫${userStore.newName}, 我是個(gè)小${
this.sex === '0' ? '姑娘' : '伙子'
}`
)
}
}
})
在組件中使用user2模塊
<script lang="ts" setup>
import { useUser2Store } from '../../store/user2'
const user2Store = useUser2Store()
setTimeout(() => {
user2Store.sayInfo('1')
}, 3000) // 3s后輸出----》 我叫李二牛, 我是個(gè)小伙子
</script>
7.devtools
在devtools中可以看到,pinia會(huì)自動(dòng)根據(jù)文件區(qū)分模塊!

4.數(shù)據(jù)持久化
開啟持久化可以在頁面刷新的時(shí)候,幫我們把數(shù)據(jù)緩存下來,不被清空。
1.安裝插件
npm i pinia-plugin-persist --save
2.引用插件
在store/index.ts引入插件,并且use
import { createPinia } from 'pinia'
import piniaPluginpersist from 'pinia-plugin-persist'
const store = createPinia()
// 使用持久化插件
store.use(piniaPluginpersist)
export default store
3.在store模塊中啟用持久化
(1) 啟用
在user.ts中啟用:添加persist配置項(xiàng)
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: (): {
userInfo: UserInfo
token: string
} => ({
userInfo: {},
token: ''
}),
getters: { ... },
actions: { ... },
// 開始數(shù)據(jù)持久化
persist: {
enabled: true
}
})
數(shù)據(jù)會(huì)默認(rèn)存儲(chǔ)到sessionStorage,可以在控制臺(tái)看到。

(2) 修改key & 存儲(chǔ)位置
默認(rèn)存儲(chǔ)到sessionStorage的key值就是store模塊id值。可以通過strategies修改key值和存儲(chǔ)位置,如:
將key值改為_user,存儲(chǔ)位置改為localStorage(注意之前緩存在sessionStorage中的數(shù)據(jù)還在,可以手動(dòng)清除一下sessionStorage.clear())
persist: {
enabled: true,
strategies: [{
key: '_user',
storage: localStorage
}]
}
在控制臺(tái)打印localStorage

(3) 自定義要持久化的字段
默認(rèn)會(huì)將store中的所有字段都緩存,可以通過paths指定要緩存的字段。
如:我只要緩存userInfo
persist: {
enabled: true,
strategies: [{
key: '_user',
storage: localStorage,
paths: ['userInfo']
}]
}
控制臺(tái)打印,可以看到token字段沒有了!

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
利用Vue與D3.js創(chuàng)建交互式數(shù)據(jù)可視化
在現(xiàn)代Web開發(fā)中,數(shù)據(jù)可視化是一個(gè)引人矚目的熱點(diǎn)領(lǐng)域,從簡(jiǎn)單的圖表到復(fù)雜的交互式儀表盤,數(shù)據(jù)可視化能夠幫助用戶更好地理解數(shù)據(jù),而Vue與D3.js的結(jié)合則為我們提供了構(gòu)建這些可視化效果的強(qiáng)大工具,本文將向您展示如何利用Vue與D3.js創(chuàng)建一個(gè)基本的交互式數(shù)據(jù)可視化項(xiàng)目2025-02-02
.netcore+vue 實(shí)現(xiàn)壓縮文件下載功能
這篇文章主要介紹了.netcore+vue 實(shí)現(xiàn)壓縮文件下載功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09
VUE 實(shí)現(xiàn)element upload上傳圖片到阿里云
這篇文章主要介紹了VUE 實(shí)現(xiàn)element upload上傳圖片到阿里云,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-08-08
vue恢復(fù)初始數(shù)據(jù)this.$data,this.$options.data()解析
這篇文章主要介紹了vue恢復(fù)初始數(shù)據(jù)this.$data,this.$options.data()解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
淺談vue的iview列表table render函數(shù)設(shè)置DOM屬性值的方法
下面小編就為大家?guī)硪黄獪\談vue的iview列表table render函數(shù)設(shè)置DOM屬性值的方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09
在vscode 中設(shè)置 vue模板內(nèi)容的方法
這篇文章主要介紹了在vscode 中設(shè)置 vue模板內(nèi)容的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09

