您好,登錄后才能下訂單哦!
這篇文章主要介紹“Vue之Pinia狀態(tài)管理的方法是什么”,在日常操作中,相信很多人在Vue之Pinia狀態(tài)管理的方法是什么問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Vue之Pinia狀態(tài)管理的方法是什么”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
Pinia開始于大概2019年,其目的是設(shè)計一個擁有 組合式 API 的 Vue 狀態(tài)管理庫
目前同時兼容Vue2、Vue3,也并不要求你使用Composition API
Pinia本質(zhì)上依然是一個狀態(tài)管理庫,用于跨組件、頁面進行狀態(tài)共享
狀態(tài)管理庫是什么?
是一個保存狀態(tài)和業(yè)務(wù)邏輯的實體,它會持有為綁定到你組件樹的狀態(tài)和業(yè)務(wù)邏輯,也就是保存了全局的狀態(tài);
它有點像一個永遠存在的組件,每個組件都可以讀取和寫入它;
你可以在你的應(yīng)用程序中定義任意數(shù)量的Store來管理你的狀態(tài);
應(yīng)該在什么時候使用 Store?
一個 Store 應(yīng)該包含可以在整個應(yīng)用中訪問的數(shù)據(jù)。這包括在許多地方使用的數(shù)據(jù),例如顯示在導(dǎo)航欄中的用戶信息,以及需要通過頁面保存的數(shù)據(jù),例如一個非常復(fù)雜的多步驟表單。
另一方面,應(yīng)該避免在 Store 中引入那些原本可以在組件中保存的本地數(shù)據(jù),例如,一個元素在頁面中的可見性。
安裝:npm install pinia
使用 Pinia,即使在小型單頁應(yīng)用中,你也可以獲得如下功能:
Devtools 支持
追蹤 actions、mutations 的時間線
在組件中展示它們所用到的 Store
讓調(diào)試更容易的 Time travel
熱更新
不必重載頁面即可修改 Store
開發(fā)時可保持當(dāng)前的 State
插件:可通過插件擴展 Pinia 功能
為 JS 開發(fā)者提供適當(dāng)?shù)?TypeScript 支持以及自動補全功能。
支持服務(wù)端渲染
Store有三個核心概念:
state、getters、actions;
等同于組件的data、computed、methods;
一旦 store 被實例化,你就可以直接在 store 上訪問 state、getters 和 actions 中定義的任何屬性;
Store 是用 defineStore() 定義的
它需要一個唯一名稱,作為第一個參數(shù)傳遞
這個名字 ,也被用作 id ,是必須傳入的, Pinia 將用它來連接 store 和 devtools。
返回的函數(shù)統(tǒng)一使用useX作為命名方案,這是約定的規(guī)范
defineStore() 的第二個參數(shù)可接受兩類值:Setup 函數(shù)或 Option 對象
import { defineStore } from 'pinia' // 你可以對 `defineStore()` 的返回值進行任意命名,但最好使用 store 的名字,同時以 `use` 開頭且以 `Store` 結(jié)尾。 // 第一個參數(shù)是你的應(yīng)用中 Store 的唯一 ID。 export const useCounterStore = defineStore('counter', { // 其他配置... })
我們也可以傳入一個帶有 state、actions 與 getters 屬性的 Option 對象:
我們可以認(rèn)為
state 是 store 的數(shù)據(jù) (data)
getters 是 store 的計算屬性 (computed)
而 actions 則是方法 (methods)
export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), getters: { double: (state) => state.count * 2, }, actions: { increment() { this.count++ }, }, })
與 Vue 組合式 API 的 setup 函數(shù) 相似
我們可以傳入一個函數(shù),該函數(shù)定義了一些響應(yīng)式屬性和方法
并且返回一個帶有我們想暴露出去的屬性和方法的對象
在 Setup Store 中:
ref()
就是 state
屬性
computed()
就是 getters
function()
就是 actions
export const useCounterStore = defineStore('counter', () => { const count = ref(0) function increment() { count.value++ } return { count, increment } })
Store在它被使用之前是不會創(chuàng)建的,我們可以通過調(diào)用**useStore()**來使用Store:
<script setup> import { useCounterStore } from '@/stores/counter' const store = useCounterStore() </script>
一旦 store 被實例化,你可以直接訪問在 store 的 state、getters 和 actions 中定義的任何屬性。
注意Store獲取到后不能被解構(gòu),那么會失去響應(yīng)式:
為了從 Store 中提取屬性同時保持其響應(yīng)式,您需要使用storeToRefs()。
state 是 store 的核心部分,因為store是用來幫助我們管理狀態(tài)的
在 Pinia 中,狀態(tài)被定義為返回初始狀態(tài)的函數(shù)
import { defineStore } from 'pinia' export const useCounter = defineStore('counter', { // 為了完整類型推理,推薦使用箭頭函數(shù) state: () => { return { // 所有這些屬性都將自動推斷出它們的類型 counter: 0 } } })
讀取和寫入State:
默認(rèn)情況下,您可以通過 store 實例訪問狀態(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
方法
它允許你用一個 state
的對象在同一時間更改多個屬性
counterStore.$patch({ counter : 1, age: 120, name: 'pack', })
// 示例文件路徑: // ./src/stores/counter.js import { defineStore } from 'pinia' const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), })
Getters 完全等同于 store 的 state 的計算屬性
可以通過 defineStore()
中的 getters
屬性來定義它們。
推薦使用箭頭函數(shù),并且它將接收 state
作為第一個參數(shù)
export const useCounter = defineStore('counter', { state: () => ({ counter: 15 }), getters: { doubleCounter: (state) => state.counter * 2 } })
訪問當(dāng)前store 實例上的 getters
const counterStore = useCounter() console.log(counterStore.doubleCounter)
Getters中訪問當(dāng)前store實例的其他Getters
我們可以通過 this
,你可以訪問到其他任何 getters
getters: { doubleCount: (state) => state.counter * 2, // 返回 counter 的值乘以 2 加 1 doubleCountPlusOne() { return this.doubleCount + 1 } }
訪問其他store實例的Getters
getters: { otherGetter(state) { const otherStore = useOtherStore() return state.localData + otherStore.data } }
Getters可以 返回一個函數(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>
Actions 相當(dāng)于組件中的 methods。
可以通過 defineStore() 中的 actions 屬性來定義,并且它們也是定義業(yè)務(wù)邏輯的完美選擇。
類似 Getters,Actions 也可通過 this 訪問整個 store 實例
export const useCounterStore = defineStore('counter', { state: () => ({ counter: 15 }), actions: { increment() { this.counter++ } } })
Actions 中是支持異步操作的,并且我們可以編寫異步函數(shù),在函數(shù)中使用await
:
Actions 可以像函數(shù)或者通常意義上的方法一樣被調(diào)用:
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') } }, }, })
到此,關(guān)于“Vue之Pinia狀態(tài)管理的方法是什么”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。