一、簡(jiǎn)介
Pinia
是 Vue
的專(zhuān)屬狀態(tài)管理庫(kù),它允許你跨組件或頁(yè)面共享狀態(tài)。它跟 Vuex
有一定的相似度,但還是有很大的區(qū)別。
愿意看這篇博客的人,想必已經(jīng)看過(guò)了官方文檔,官方文檔很詳細(xì),包含各種使用情景和理論,因此本文不說(shuō)理論,只說(shuō)具體的使用方法,想深入研究的建議去看官方文檔,本文適合拿來(lái)即用。
Pinia 官方文檔
二、使用方法
1. 安裝
yarn add pinia
# 或者使用 npm
npm install pinia
2. 引入
main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
createApp(App).use(pinia).mount('#app') // vue3 的簡(jiǎn)寫(xiě)語(yǔ)法
不熟悉vue3簡(jiǎn)寫(xiě)語(yǔ)法的可以按照下面的方式去寫(xiě),效果是一樣的
main.ts
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. 創(chuàng)建文件
在 src
文件中,創(chuàng)建 store
文件,里面按模塊創(chuàng)建 ts
文件(也可以是 js
)。
注意: pinia
不需要?jiǎng)?chuàng)建 modules
文件來(lái)區(qū)分模塊化,這是它和 vuex
的區(qū)別。
以登錄后保存用戶(hù)信息模塊舉例:
注意: 命名方式建議統(tǒng)一規(guī)范 use + id + store
,示例 useUserStore
,id
為 user
。
store/user.ts
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
userInfo: {}
}),
actions: {
SetUserInfo(data: any) {
this.userInfo = data
}
}
})
4. 使用
先引入模塊,再將引入的模塊對(duì)象賦值給變量 store
(命名隨意),如果不需要修改數(shù)據(jù),用 const
聲明變量,需要修改數(shù)據(jù)則使用 let
聲明。
注意:引入的模塊對(duì)象名要與模塊中 export const
聲明的一致。
.ts or .vue
import { useUserStore } from '@/store/user'
const store: any = useUserStore()
console.log(store.userInfo)
5. 修改數(shù)據(jù)
修改數(shù)據(jù)多種方法,可以直接修改,也可以使用 actions 修改。
方法1:直接修改
.ts or .vue
import { useUserStore } from '@/store/user'
const store = useUserStore()
store.userInfo = obj // obj 指新值
方法2:借助 actions 修改
.ts or .vue
import { useUserStore } from '@/store/user'
const store = useUserStore()
store.SetUserInfo(obj) // obj 指新值
方法3:多屬性修改
store/user.ts
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: null,
age: null,
sex: null,
}),
})
上面的方法都是用來(lái)修改單個(gè)屬性的,如果你需要一次修改多個(gè)屬性,雖然你可以重復(fù)操作上面的方法,但是 pinia 提供了新的方法,我更推薦使用官方推薦的方法。
.ts or .vue
import { useUserStore } from '@/store/user'
const store = useUserStore()
// 你可以這樣去修改(不建議)
store.name = '張三'
store.age = 24
store.sex = '男'
// 推薦使用下面這種方式 √
store.$patch({
name: '張三',
age: 24,
sex: '男',
})
修改數(shù)據(jù)的場(chǎng)景及方法當(dāng)然不止這些,有些復(fù)雜的數(shù)據(jù)修改僅靠這些是難以實(shí)現(xiàn)的,不過(guò)本文的目的是簡(jiǎn)單講解 pinia
的使用方法,就不多做贅述了,想具體了解推薦去看 Pinia 官方文檔。
三、持久化存儲(chǔ)
PS:持久化插件推薦文末修正,pinia-plugin-persist
插件在 TypeScript
中出現(xiàn)類(lèi)型聲明問(wèn)題。不影響使用,但會(huì)有預(yù)警提示。2023-12-08
pinia
和 vuex
一樣,數(shù)據(jù)是短時(shí)的,只要一刷新頁(yè)面,數(shù)據(jù)就會(huì)恢復(fù)成初始狀態(tài),為了避免這個(gè)問(wèn)題,可以對(duì)其采用持久化保存方法。
持久化保存的原理是在 pinia
中數(shù)據(jù)更新時(shí),同步保存到 localStorage
或 sessionStorage
中,刷新后從本地存儲(chǔ)中讀取數(shù)據(jù),你可以選擇自己去寫(xiě),但是實(shí)現(xiàn)起來(lái)并不像想象中那么容易,當(dāng)然,也沒(méi)那么難。
我推薦使用插件去實(shí)現(xiàn)持久化存儲(chǔ),這樣更便捷,省時(shí)省力。推薦插件為 pinia-plugin-persist,當(dāng)然,實(shí)現(xiàn)持久化存儲(chǔ)的插件肯定不止這一種,想用別的也無(wú)所謂,本文僅對(duì)這款插件講解使用方法。
1. 安裝插件
yarn add pinia-plugin-persist
# 或者使用 npm
npm install pinia-plugin-persist
2. 引入插件
和引入 pinia
一樣,在 main.ts
中引入。
mian.ts
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'
const pinia = createPinia()
pinia.use(piniaPersist)
createApp(App).use(pinia).mount('#app')
3. 使用插件
方式1:默認(rèn)保存
下面這種寫(xiě)法會(huì)將當(dāng)前模塊中的所有數(shù)據(jù)都進(jìn)行持久化保存,默認(rèn)保存在 sessionStorage
中, key
為模塊 id
,刷新頁(yè)面不需要手動(dòng)讀取數(shù)據(jù),插件會(huì)自動(dòng)讀取。
store/user.ts
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: null,
age: null,
sex: null,
}),
persist: {
enabled: true // true 表示開(kāi)啟持久化保存
}
})
方式2:設(shè)置 key 、指定保存內(nèi)容
你可以主動(dòng)設(shè)置 key
名,也可以指定哪些數(shù)據(jù)保存,默認(rèn)會(huì)保存當(dāng)前模塊全部數(shù)據(jù)。
store/user.ts
export const useUserStore = defineStore('storeUser', {
state: () => ({
name: null,
age: null,
sex: null,
}),
persist: {
enabled: true,
strategies: [
{
key: 'user',
storage: localStorage,
paths: ['name']
},
],
},
})
你甚至可以對(duì)不同數(shù)據(jù)設(shè)置不同的本地存儲(chǔ)方式。
store/user.ts
export const useUserStore = defineStore('storeUser', {
state: () => ({
name: null,
age: null,
sex: null,
}),
persist: {
enabled: true,
strategies: [
{ storage: sessionStorage, paths: ['name'] },
{ storage: localStorage, paths: ['age'] },
],
},
})
方式3:保存到 cookie
保存到 cookie
中當(dāng)然也是可以的,不過(guò)需要手動(dòng)添加 cookie
的保存方式,同樣,此處也是推薦使用插件 js-cookie 來(lái)完成。
npm install js-cookie
store/user.ts
import Cookies from 'js-cookie'
const cookiesStorage: Storage = {
setItem (key, state) {
return Cookies.set(key, state.accessToken, { expires: 3 }) // 設(shè)置有效期 3 天,不設(shè)置默認(rèn)同 sessionStorage 有效期一致
},
getItem (key) {
return JSON.stringify({
accessToken: Cookies.get(key),
})
},
}
export const useUserStore = defineStore('storeUser', {
state: () => ({
name: null,
age: null,
sex: null,
accessToken: 'xxxxxxxxx',
}),
persist: {
enabled: true,
strategies: [
{
storage: cookiesStorage,
paths: ['accessToken'] // cookie 一般用來(lái)保存 token
},
],
},
})
四、2023-12-08更新:持久化存儲(chǔ)插件推薦修改
以下內(nèi)容為 2023-12-08 更新。
pinia-plugin-persist
在 typeScript 中有類(lèi)型聲明問(wèn)題。推薦插件改為 pinia-plugin-persistedstate
。官網(wǎng)地址如下:
pinia-plugin-persistedstate 中文官網(wǎng)
官網(wǎng)的文檔非常詳細(xì),且使用方法與 pinia-plugin-persist
類(lèi)似,因此本文不做過(guò)多贅述,僅簡(jiǎn)要描述下使用方法。
1、安裝插件
npm i pinia-plugin-persistedstate
2、引入插件
main.ts
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
3、使用插件
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => {
return {
someState: '你好 pinia',
}
},
persist: true,
})
只需要添加 persist: true
, 整個(gè) store
都將被持久化存儲(chǔ)。
當(dāng)然也可以指定部分?jǐn)?shù)據(jù)持久化,方法如下:
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: null,
age: null,
sex: null,
info: {
des: null
}
}),
persist: {
paths: ['name', 'info.des'],
},
})
這樣則只有 name
,info.des
被持久化保存了。
文章到此就結(jié)束了,如果有需要作者補(bǔ)充或修正的,歡迎在評(píng)論區(qū)留言。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-481380.html
END文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-481380.html
到了這里,關(guān)于Pinia使用方法及持久化存儲(chǔ)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!