[轉(zhuǎn)載]新一代狀態(tài)管理工具,Pinia.js 上手指南

前言

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 也比較簡單,引入對(duì)應(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

接著在對(duì)應(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文檔

作者:小學(xué)生study
鏈接:https://juejin.cn/post/7049196967770980389
來源:稀土掘金
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容