Vue之Pinia狀態(tài)管理
一、認(rèn)識(shí)Pinia
1.1 認(rèn)識(shí)Pinia
- Pinia開始于大概2019年,其目的是設(shè)計(jì)一個(gè)擁有 組合式 API 的 Vue 狀態(tài)管理庫(kù)
- 目前同時(shí)兼容Vue2、Vue3,也并不要求你使用Composition API
- Pinia本質(zhì)上依然是一個(gè)狀態(tài)管理庫(kù),用于跨組件、頁(yè)面進(jìn)行狀態(tài)共享
狀態(tài)管理庫(kù)是什么?
- 是一個(gè)保存狀態(tài)和業(yè)務(wù)邏輯的實(shí)體,它會(huì)持有為綁定到你組件樹的狀態(tài)和業(yè)務(wù)邏輯,也就是保存了全局的狀態(tài);
- 它有點(diǎn)像一個(gè)永遠(yuǎn)存在的組件,每個(gè)組件都可以讀取和寫入它;
- 你可以在你的應(yīng)用程序中定義任意數(shù)量的Store來管理你的狀態(tài);
應(yīng)該在什么時(shí)候使用 Store?
- 一個(gè) Store 應(yīng)該包含可以在整個(gè)應(yīng)用中訪問的數(shù)據(jù)。這包括在許多地方使用的數(shù)據(jù),例如顯示在導(dǎo)航欄中的用戶信息,以及需要通過頁(yè)面保存的數(shù)據(jù),例如一個(gè)非常復(fù)雜的多步驟表單。
- 另一方面,應(yīng)該避免在 Store 中引入那些原本可以在組件中保存的本地?cái)?shù)據(jù),例如,一個(gè)元素在頁(yè)面中的可見性。
安裝:npm install pinia
1.2 為什么使用Pinia?
使用 Pinia,即使在小型單頁(yè)應(yīng)用中,你也可以獲得如下功能:
- Devtools 支持
- 追蹤 actions、mutations 的時(shí)間線
- 在組件中展示它們所用到的 Store
- 讓調(diào)試更容易的 Time travel
- 熱更新
- 不必重載頁(yè)面即可修改 Store
- 開發(fā)時(shí)可保持當(dāng)前的 State
- 插件:可通過插件擴(kuò)展 Pinia 功能
- 為 JS 開發(fā)者提供適當(dāng)?shù)?TypeScript 支持以及自動(dòng)補(bǔ)全功能。
- 支持服務(wù)端渲染
二、 Store
Store有三個(gè)核心概念:
- state、getters、actions;
- 等同于組件的data、computed、methods;
- 一旦 store 被實(shí)例化,你就可以直接在 store 上訪問 state、getters 和 actions 中定義的任何屬性;
2.1 定義Store
Store 是用 defineStore() 定義的
- 它需要一個(gè)唯一名稱,作為第一個(gè)參數(shù)傳遞
- 這個(gè)名字 ,也被用作 id ,是必須傳入的, Pinia 將用它來連接 store 和 devtools。
- 返回的函數(shù)統(tǒng)一使用useX作為命名方案,這是約定的規(guī)范
- defineStore() 的第二個(gè)參數(shù)可接受兩類值:Setup 函數(shù)或 Option 對(duì)象
import { defineStore } from 'pinia' // 你可以對(duì) `defineStore()` 的返回值進(jìn)行任意命名,但最好使用 store 的名字,同時(shí)以 `use` 開頭且以 `Store` 結(jié)尾。 // 第一個(gè)參數(shù)是你的應(yīng)用中 Store 的唯一 ID。 export const useCounterStore = defineStore('counter', { // 其他配置... })
2.2 Option對(duì)象
我們也可以傳入一個(gè)帶有 state、actions 與 getters 屬性的 Option 對(duì)象:
- 我們可以認(rèn)為
- state 是 store 的數(shù)據(jù) (data)
- getters 是 store 的計(jì)算屬性 (computed)
- 而 actions 則是方法 (methods)
export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), getters: { double: (state) => state.count * 2, }, actions: { increment() { this.count++ }, }, })
2.3 setup函數(shù)
與 Vue 組合式 API 的 setup 函數(shù) 相似
- 我們可以傳入一個(gè)函數(shù),該函數(shù)定義了一些響應(yīng)式屬性和方法
- 并且返回一個(gè)帶有我們想暴露出去的屬性和方法的對(duì)象
- 在 Setup Store 中:
ref()
就是state
屬性computed()
就是getters
function()
就是actions
export const useCounterStore = defineStore('counter', () => { const count = ref(0) function increment() { count.value++ } return { count, increment } })
2.4 使用定義的Store
Store在它被使用之前是不會(huì)創(chuàng)建的,我們可以通過調(diào)用**useStore()**來使用Store:
<script setup> import { useCounterStore } from '@/stores/counter' const store = useCounterStore() </script>
- 一旦 store 被實(shí)例化,你可以直接訪問在 store 的 state、getters 和 actions 中定義的任何屬性。
- 注意Store獲取到后不能被解構(gòu),那么會(huì)失去響應(yīng)式:
- 為了從 Store 中提取屬性同時(shí)保持其響應(yīng)式,您需要使用storeToRefs()。
三、Pinia核心概念State
3.1 定義State
state 是 store 的核心部分,因?yàn)閟tore是用來幫助我們管理狀態(tài)的
- 在 Pinia 中,狀態(tài)被定義為返回初始狀態(tài)的函數(shù)
import { defineStore } from 'pinia' export const useCounter = defineStore('counter', { // 為了完整類型推理,推薦使用箭頭函數(shù) state: () => { return { // 所有這些屬性都將自動(dòng)推斷出它們的類型 counter: 0 } } })
3.2 操作State
讀取和寫入State:
- 默認(rèn)情況下,您可以通過 store 實(shí)例訪問狀態(tài)來直接讀取和寫入狀態(tài)
const counterStore = useCounter() counterStore.$reset()
重置State
- 你可以通過調(diào)用 store 上的 $reset() 方法將狀態(tài) 重置 到其初始值
const counterStore = useCounter() counterStore.$reset()
變更State
- 除了用
store.count++
直接改變 store,你還可以調(diào)用$patch
方法 - 它允許你用一個(gè)
state
的對(duì)象在同一時(shí)間更改多個(gè)屬性
counterStore.$patch({ counter : 1, age: 120, name: 'pack', })
3.3 使用選項(xiàng)式 API 的用法
// 示例文件路徑: // ./src/stores/counter.js import { defineStore } from 'pinia' const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), })
四、Pinia核心概念Getters
4.1 認(rèn)識(shí)Getters
Getters 完全等同于 store 的 state 的計(jì)算屬性
- 可以通過
defineStore()
中的getters
屬性來定義它們。 - 推薦使用箭頭函數(shù),并且它將接收
state
作為第一個(gè)參數(shù)
export const useCounter = defineStore('counter', { state: () => ({ counter: 15 }), getters: { doubleCounter: (state) => state.counter * 2 } })
4.2 訪問Getters
訪問當(dāng)前store 實(shí)例上的 getters
const counterStore = useCounter() console.log(counterStore.doubleCounter)
Getters中訪問當(dāng)前store實(shí)例的其他Getters
- 我們可以通過
this
,你可以訪問到其他任何 getters
getters: { doubleCount: (state) => state.counter * 2, // 返回 counter 的值乘以 2 加 1 doubleCountPlusOne() { return this.doubleCount + 1 } }
訪問其他store實(shí)例的Getters
getters: { otherGetter(state) { const otherStore = useOtherStore() return state.localData + otherStore.data } }
4.3 向Getters傳遞參數(shù)
Getters可以 返回一個(gè)函數(shù),該函數(shù)可以接受任意參數(shù):
export const useUserListStore = defineStore('main', { state: () => ({ users: [ { id: 1, name: 'lisa' }, { id: 2, name: 'pack' } ] }), getters: { getUserById: (state) => { return (userId) => { state.users.find((user) => user.id === userId) } } } })
在組件中使用:
<template> <p>User 2: {{ getUserById(2) }}</p> </template> <script setup> import { useUserListStore } from './store' const userList = useUserListStore() const { getUserById } = storeToRefs(userList) </script>
五、Pinia核心概念A(yù)ctions
5.1 認(rèn)識(shí)Actions
Actions 相當(dāng)于組件中的 methods。
- 可以通過 defineStore() 中的 actions 屬性來定義,并且它們也是定義業(yè)務(wù)邏輯的完美選擇。
- 類似 Getters,Actions 也可通過 this 訪問整個(gè) store 實(shí)例
export const useCounterStore = defineStore('counter', { state: () => ({ counter: 15 }), actions: { increment() { this.counter++ } } })
5.2 Actions執(zhí)行異步操作
Actions 中是支持異步操作的,并且我們可以編寫異步函數(shù),在函數(shù)中使用await
:
Actions 可以像函數(shù)或者通常意義上的方法一樣被調(diào)用:
5.3 訪問其他 store 的 Actions
import { useAuthStore } from './auth-store' export const useSettingsStore = defineStore('settings', { state: () => ({ preferences: null, // ... }), actions: { async fetchUserPreferences() { const auth = useAuthStore() if (auth.isAuthenticated) { this.preferences = await fetchPreferences() } else { throw new Error('User must be authenticated') } }, }, })
以上就是Vue之Pinia狀態(tài)管理的詳細(xì)內(nèi)容,更多關(guān)于Pinia狀態(tài)管理的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue 引入AMap高德地圖的實(shí)現(xiàn)代碼
這篇文章主要介紹了Vue 引入AMap高德地圖的實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04在vue項(xiàng)目中 實(shí)現(xiàn)定義全局變量 全局函數(shù)操作
這篇文章主要介紹了在vue項(xiàng)目中 實(shí)現(xiàn)定義全局變量 全局函數(shù)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-10-10vue動(dòng)態(tài)綁定ref(使用變量)以及獲取方式
這篇文章主要介紹了vue動(dòng)態(tài)綁定ref(使用變量)以及獲取方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08vue動(dòng)態(tài)合并單元格并添加小計(jì)合計(jì)功能示例
這篇文章主要給大家介紹了關(guān)于vue動(dòng)態(tài)合并單元格并添加小計(jì)合計(jì)功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11