Vue3學習筆記(七)—— 狀態管理、Vuex、Pinia

一、狀態管理

1.1、什麼是狀態管理?

理論上來說,每一個 Vue 組件實例都已經在“管理”它自己的響應式狀態了。我們以一個簡單的計數器組件爲例:

<script setup>
import { ref } from 'vue'

// 狀態
const count = ref(0)

// 動作
function increment() {
  count.value++
}
</script>

<!-- 視圖 -->
<template>{{ count }}</template>

它是一個獨立的單元,由以下幾個部分組成:

  • 狀態:驅動整個應用的數據源;
  • 視圖:對狀態的一種聲明式映射;
  • 交互:狀態根據用戶在視圖中的輸入而作出相應變更的可能方式。

下面是“單向數據流”這一概念的簡單圖示:

state flow diagram

然而,當我們有多個組件共享一個共同的狀態時,就沒有這麼簡單了:

  1. 多個視圖可能都依賴於同一份狀態。
  2. 來自不同視圖的交互也可能需要更改同一份狀態。

對於情景 1,一個可行的辦法是將共享狀態“提升”到共同的祖先組件上去,再通過 props 傳遞下來。然而在深層次的組件樹結構中這麼做的話,很快就會使得代碼變得繁瑣冗長。這會導致另一個問題:Prop 逐級透傳問題

對於情景 2,我們經常發現自己會直接通過模板引用獲取父/子實例,或者通過觸發的事件嘗試改變和同步多個狀態的副本。但這些模式的健壯性都不甚理想,很容易就會導致代碼難以維護。

一個更簡單直接的解決方案是抽取出組件間的共享狀態,放在一個全局單例中來管理。這樣我們的組件樹就變成了一個大的“視圖”,而任何位置上的組件都可以訪問其中的狀態或觸發動作。

1.2、用響應式 API 做簡單狀態管理

如果你有一部分狀態需要在多個組件實例間共享,你可以使用 reactive() 來創建一個響應式對象,並將它導入到多個組件中:

// store.js
import { reactive } from 'vue'

export const store = reactive({
  count: 0
})
<!-- ComponentA.vue -->
<script setup>
import { store } from './store.js'
</script>

<template>From A: {{ store.count }}</template>
<!-- ComponentB.vue -->
<script setup>
import { store } from './store.js'
</script>

<template>From B: {{ store.count }}</template>

現在每當 store 對象被更改時,<ComponentA> 與 <ComponentB> 都會自動更新它們的視圖。現在我們有了單一的數據源。

然而,這也意味着任意一個導入了 store 的組件都可以隨意修改它的狀態:

<template>
  <button @click="store.count++">
    From B: {{ store.count }}
  </button>
</template>

雖然這在簡單的情況下是可行的,但從長遠來看,可以被任何組件任意改變的全局狀態是不太容易維護的。爲了確保改變狀態的邏輯像狀態本身一樣集中,建議在 store 上定義方法,方法的名稱應該要能表達出行動的意圖:

// store.js
import { reactive } from 'vue'

export const store = reactive({
  count: 0,
  increment() {
    this.count++
  }
})
<template>
  <button @click="store.increment()">
    From B: {{ store.count }}
  </button>
</template>

CounterA.vue

<template>
  <div class="counter">
    <h2>計數器A - {{ mystore.n }}</h2>
    <button @click="mystore.increment(1)">每次點擊增加1</button>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { mystore } from "../mystore";
</script>
<style scoped>
.counter {
  background: #def;
}
</style>

CounterB.vue

<template>
  <div class="counter">
    <h2>計數器B - {{ mystore.n }}</h2>
    <button @click="mystore.increment(2)">每次點擊增加2</button>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { mystore } from "../mystore";
</script>
<style scoped>
.counter {
  background: #dfe;
}
</style>

App.vue

<template>
  <CounterA />
  <CounterB />
</template>

<script lang="ts" setup>
import CounterA from "./components/CounterA.vue";
import CounterB from "./components/CounterB.vue";
</script>

<style></style>

TIP

請注意這裏點擊的處理函數使用了 store.increment(),帶上了圓括號作爲內聯表達式調用,因爲它並不是組件的方法,並且必須要以正確的 this 上下文來調用。

除了我們這裏用到的單個響應式對象作爲一個 store 之外,你還可以使用其他響應式 API 例如 ref() 或是 computed(),或是甚至通過一個組合式函數來返回一個全局狀態:

import { ref } from 'vue'

// 全局狀態,創建在模塊作用域下
const globalCount = ref(1)

export function useCount() {
  // 局部狀態,每個組件都會創建
  const localCount = ref(1)

  return {
    globalCount,
    localCount
  }
}

事實上,Vue 的響應性系統與組件層是解耦的,這使得它非常靈活。

CounterA.vue

<template>
  <div class="counter">
    <h2>計數器A - global={{ store.global }} local={{ store.local }}</h2>
    <button @click="store.incrementGlobal">全局增加1</button>
    <button @click="store.incrementLocal">局部增加1</button>
  </div>
</template>
<script lang="ts" setup>
import { useStore } from "../mystore";
const store = useStore();
</script>
<style scoped>
.counter {
  background: #def;
}
</style>

CounterB.vue

<template>
  <div class="counter">
    <h2>計數器B - global={{ store.global }} local={{ store.local }}</h2>
    <button @click="store.incrementGlobal">全局增加1</button>
    <button @click="store.incrementLocal">局部增加1</button>
  </div>
</template>
<script lang="ts" setup>
import { useStore } from "../mystore";
const store = useStore();
</script>
<style scoped>
.counter {
  background: #dfe;
}
</style>

App.vue

<template>
  <CounterA />
  <CounterB />
</template>

<script lang="ts" setup>
import CounterA from "./components/CounterA.vue";
import CounterB from "./components/CounterB.vue";
</script>

<style></style>

運行結果:

1.3、SSR 相關細節

如果你正在構建一個需要利用服務端渲染 (SSR) 的應用,由於 store 是跨多個請求共享的單例,上述模式可能會導致問題。這在 SSR 指引那一章節會討論更多細節

1.4、Pinia 與 VueX

雖然我們的手動狀態管理解決方案在簡單的場景中已經足夠了,但是在大規模的生產應用中還有很多其他事項需要考慮:

  • 更強的團隊協作約定
  • 與 Vue DevTools 集成,包括時間軸、組件內部審查和時間旅行調試
  • 模塊熱更新 (HMR)
  • 服務端渲染支持

Pinia 就是一個實現了上述需求的狀態管理庫,由 Vue 核心團隊維護,對 Vue 2 和 Vue 3 都可用。

現有用戶可能對 Vuex 更熟悉,它是 Vue 之前的官方狀態管理庫。由於 Pinia 在生態系統中能夠承擔相同的職責且能做得更好,因此 Vuex 現在處於維護模式。它仍然可以工作,但不再接受新的功能。對於新的應用,建議使用 Pinia。

事實上,Pinia 最初正是爲了探索 Vuex 的下一個版本而開發的,因此整合了核心團隊關於 Vuex 5 的許多想法。最終,我們意識到 Pinia 已經實現了我們想要在 Vuex 5 中提供的大部分內容,因此決定將其作爲新的官方推薦。

相比於 Vuex,Pinia 提供了更簡潔直接的 API,並提供了組合式風格的 API,最重要的是,在使用 TypeScript 時它提供了更完善的類型推導。

二、Vuex

Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式 + 庫。它採用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。

2.1、什麼是“狀態管理模式”?

讓我們從一個簡單的 Vue 計數應用開始:

const Counter = {
  // 狀態
  data () {
    return {
      count: 0
    }
  },
  // 視圖
  template: `
    <div>{{ count }}</div>
  `,
  // 操作
  methods: {
    increment () {
      this.count++
    }
  }
}

createApp(Counter).mount('#app')

這個狀態自管理應用包含以下幾個部分:

  • 狀態,驅動應用的數據源;
  • 視圖,以聲明方式將狀態映射到視圖;
  • 操作,響應在視圖上的用戶輸入導致的狀態變化。

以下是一個表示“單向數據流”理念的簡單示意:

但是,當我們的應用遇到多個組件共享狀態時,單向數據流的簡潔性很容易被破壞:

  • 多個視圖依賴於同一狀態。
  • 來自不同視圖的行爲需要變更同一狀態。

對於問題一,傳參的方法對於多層嵌套的組件將會非常繁瑣,並且對於兄弟組件間的狀態傳遞無能爲力。對於問題二,我們經常會採用父子組件直接引用或者通過事件來變更和同步狀態的多份拷貝。以上的這些模式非常脆弱,通常會導致無法維護的代碼。

因此,我們爲什麼不把組件的共享狀態抽取出來,以一個全局單例模式管理呢?在這種模式下,我們的組件樹構成了一個巨大的“視圖”,不管在樹的哪個位置,任何組件都能獲取狀態或者觸發行爲!

通過定義和隔離狀態管理中的各種概念並通過強制規則維持視圖和狀態間的獨立性,我們的代碼將會變得更結構化且易維護。

這就是 Vuex 背後的基本思想,借鑑了 FluxRedux 和 The Elm Architecture。與其他模式不同的是,Vuex 是專門爲 Vue.js 設計的狀態管理庫,以利用 Vue.js 的細粒度數據響應機制來進行高效的狀態更新。

vuex

2.2、什麼情況下我應該使用 Vuex

Vuex 可以幫助我們管理共享狀態,並附帶了更多的概念和框架。這需要對短期和長期效益進行權衡。

如果您不打算開發大型單頁應用,使用 Vuex 可能是繁瑣冗餘的。確實是如此——如果您的應用夠簡單,您最好不要使用 Vuex。一個簡單的 store 模式就足夠您所需了。但是,如果您需要構建一箇中大型單頁應用,您很可能會考慮如何更好地在組件外部管理狀態,Vuex 將會成爲自然而然的選擇。引用 Redux 的作者 Dan Abramov 的話說就是:

Flux 架構就像眼鏡:您自會知道什麼時候需要它。

2.3、第一個Vuex示例

 假定我實現兩個計數器CountA,與CountB,A每次增加1,B每次增加2,使用傳統的方式實現:

CountA.vue

<template>
  <div class="container">
    <h2>計算器A - {{ n }}</h2>
    <button @click="add(1)">每次點擊加1,當前值:{{ n }}</button>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";

let n = ref(0);
function add(i) {
  n.value += i;
}
</script>
<style scoped>
.container {
  background: #def;
}
</style>

CountB.vue

<template>
  <div class="container">
    <h2>計算器B - {{ n }}</h2>
    <button @click="add(2)">每次點擊加2,當前值:{{ n }}</button>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";

let n = ref(0);
function add(i) {
  n.value += i;
}
</script>
<style scoped>
.container {
  background: #dfe;
}
</style>

此時可以發現這兩個Counter的值是獨立的,並沒有共享,如果需要共享一個狀態怎麼辦?

當然可以使用1.2用響應式 API 做簡單狀態管理,但vuex更加強大,依賴vuex:

2.3.1、添加依賴

方法一:

在腳手架 創建項目時勾選vuex的選項系統會自動創建

方法二:npm  或Yarn安裝

npm install vuex@next --save
yarn add vuex@next --save

2.3.2、定義存儲對象

src/store/index.ts

import {createStore} from 'vuex'

export default createStore({
    //數據
    state:{
        n:0
    },
    //操作state的方法
    mutations:{
        increment(state,i){
            state.n+=i;
        }
    }
});

2.3.3、使用存儲對象

CountA

<template>
  <div class="container">
    <h2>計算器A - {{ store.state.n }}</h2>
    <button @click="add(1)">每次點擊加1,當前值:{{ store.state.n }}</button>
  </div>
</template>
<script lang="ts" setup>
import { useStore } from "vuex";

const store = useStore();

function add(i) {
  store.commit("increment", i);
}
</script>
<style scoped>
.container {
  background: #def;
}
</style>

CountB

<template>
  <div class="container">
    <h2>計算器B - {{ store.state.n }}</h2>
    <button @click="add(2)">每次點擊加2,當前值:{{ store.state.n }}</button>
  </div>
</template>
<script lang="ts" setup>
import { useStore } from "vuex";

const store = useStore();

function add(i) {
  store.commit("increment", i);
}
</script>
<style scoped>
.container {
  background: #dfe;
}
</style>

App.vue

<template>
  <CountA />
  <CountB />
</template>

<script lang="ts" setup>
import CountA from "./components/CountA.vue";
import CountB from "./components/CountB.vue";
</script>

<style scoped></style>

運行結果:

 從運行結果可以看出兩個組件是共用了n,修改n的狀態是並沒有直接操作n。

2.4、state 數據

state:vuex的基本數據,用來存儲變量

提供唯一的公共數據源,所有共享的數據統一放到store的state進行儲存,相似與data。

Vuex 使用單一狀態樹——是的,用一個對象就包含了全部的應用層級狀態。至此它便作爲一個“唯一數據源 (SSOT)”而存在。這也意味着,每個應用將僅僅包含一個 store 實例。單一狀態樹讓我們能夠直接地定位任一特定的狀態片段,在調試的過程中也能輕易地取得整個當前應用狀態的快照。

單狀態樹和模塊化並不衝突——在後面的章節裏我們會討論如何將狀態和狀態變更事件分佈到各個子模塊中。

存儲在 Vuex 中的數據和 Vue 實例中的 data 遵循相同的規則,例如狀態對象必須是純粹 (plain) 的。

2.4.1、定義state

import {createStore} from 'vuex'

export default createStore({
    //數據
    state:{
        n:0,
        user:{
            name:"tom",
            age:18
        }
    },
    //操作state的方法
    mutations:{
        increment(state,i){
            state.n+=i;
        }
    }
});

2.4.2、獲取state方法一

組件內直接使用$store獲取實例:

  <div class="container">
    <h2>計算器A - {{ $store.state.n }}</h2>
    <button @click="$store.state.n += 1">
      每次點擊加1,當前值:{{ $store.state.n }}
    </button>
  </div>

2.4.3、獲取state方法二

可以通過調用 useStore 函數,來在 setup 鉤子函數中訪問 store。這與在組件中使用選項式 API 訪問 this.$store 是等效的。

import { useStore } from 'vuex'

export default {
  setup () {
    const store = useStore()
  }
}

2.4.4、獲取state方法三

使用this.$store訪問,如

export default {
  computed: {
    count() {
      return this.$store.state.n;
    },
  },
};

2.4.4、mapState映射數據

示例:直接在頁面中使用$store.state.count,結果非常麻煩:

import {createStore} from 'vuex'

export default createStore({
    //數據
    state:{
        n:0,
        count:100,
        price:985,
        user:{
            name:"tom",
            age:18
        }
    },
    //操作state的方法
    mutations:{
        increment(state,i){
            state.n+=i;
        }
    }
});

示例:使用計算屬性,工作量依然非常大

  computed: {
    count() {
      return this.$store.state.count;
    },
    price() {
      return this.$store.state.price;
    },
  },

示例:直接使用mapState映射

computed: mapState(["count", "price"]),
computed:{...mapState(["count","price"])},

當一個組件需要獲取多個狀態的時候,將這些狀態都聲明爲計算屬性會有些重複和冗餘。爲了解決這個問題,我們可以使用 mapState 輔助函數幫助我們生成計算屬性,讓你少按幾次鍵:

// 在單獨構建的版本中輔助函數爲 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭頭函數可使代碼更簡練
    count: state => state.count,

    // 傳字符串參數 'count' 等同於 `state => state.count`
    countAlias: 'count',

    // 爲了能夠使用 `this` 獲取局部狀態,必須使用常規函數
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}

當映射的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給 mapState 傳一個字符串數組。

computed: mapState([
  // 映射 this.count 爲 store.state.count
  'count'
])
<template>
  <div class="counter">
    <h2>計數器A</h2>
    <!-- <h3>count={{ count }}</h3>
    <h3>price={{ price }}</h3>
    <h3>user={{ user }}</h3>
    <h3>msg={{ msg }}</h3> -->

    <h3>priceAndCount={{ priceAndCount }}</h3>
    <h3>mycount={{ mycount }}</h3>
    <h3>getPrice={{ getPrice }}</h3>
  </div>
</template>
<script lang="ts">
import { mapState } from "vuex";

export default {
  /*1
  computed: {
    count(this: any) {
      return this.$store.state.count;
    },
    price(this: any) {
      return this.$store.state.price;
    },
  },
  */

  /*2
  computed: mapState(["count", "price", "user"]),
  */

  /*3
  computed: {
    msg() {
      return "一些消息";
    },
    ...mapState(["count", "price", "user"]),
  },
  */

  computed: mapState({
    priceAndCount: (state) => state.price + " - " + state.count,
    mycount: "count",
    getPrice(state: any) {
      return state.price;
    },
  }),
};
</script>
<style scoped>
.counter {
  background: #def;
}
</style>

2.4.5、組件仍然保有局部狀態

使用 Vuex 並不意味着你需要將所有的狀態放入 Vuex。雖然將所有的狀態放到 Vuex 會使狀態變化更顯式和易調試,但也會使代碼變得冗長和不直觀。如果有些狀態嚴格屬於單個組件,最好還是作爲組件的局部狀態。你應該根據你的應用開發需要進行權衡和確定。

2.5、getter 計算屬性

getter:從基本數據(state)派生的數據,相當於state的計算屬性

2.5.1、Getter

有時候我們需要從 store 中的 state 中派生出一些狀態,例如對列表進行過濾並計數:

computed: {
  doneTodosCount () {
    return this.$store.state.todos.filter(todo => todo.done).length
  }
}

如果有多個組件需要用到此屬性,我們要麼複製這個函數,或者抽取到一個共享函數然後在多處導入它——無論哪種方式都不是很理想。

Vuex 允許我們在 store 中定義“getter”(可以認爲是 store 的計算屬性)。

注意

從 Vue 3.0 開始,getter 的結果不再像計算屬性一樣會被緩存起來。這是一個已知的問題,將會在 3.1 版本中修復。

Getter 接受 state 作爲其第一個參數:

const store = createStore({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos (state) {
      return state.todos.filter(todo => todo.done)
    }
  }
})

2.5.2、通過屬性訪問

Getter 會暴露爲 store.getters 對象,你可以以屬性的形式訪問這些值:

store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

Getter 也可以接受其他 getter 作爲第二個參數:

getters: {
  // ...
  doneTodosCount (state, getters) {
    return getters.doneTodos.length
  }
}
store.getters.doneTodosCount // -> 1

我們可以很容易地在任何組件中使用它:

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

注意,getter 在通過屬性訪問時是作爲 Vue 的響應式系統的一部分緩存其中的。

2.5.3、通過方法訪問

你也可以通過讓 getter 返回一個函數,來實現給 getter 傳參。在你對 store 裏的數組進行查詢時非常有用。

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

注意,getter 在通過方法訪問時,每次都會去進行調用,而不會緩存結果。

2.5.4、mapGetters 輔助函數

mapGetters 輔助函數僅僅是將 store 中的 getter 映射到局部計算屬性:

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用對象展開運算符將 getter 混入 computed 對象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

如果你想將一個 getter 屬性另取一個名字,使用對象形式:

...mapGetters({
  // 把 `this.doneCount` 映射爲 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})
import {createStore} from 'vuex';

//創建存儲對象
export default createStore({
    //狀態,相當於data,數據
    state:{
        count:100,
        price:95.7,
        user:{
            name:"tom",
            age:18
        },
        todos:[
            {id:1,name:"健身",done:false},
            {id:2,name:"閱讀",done:true},
            {id:1,name:"整理",done:true},
        ]
    },
    //計算屬性,對state的加工
    getters:{
        countAndPrice(state){
            return state.count+"_"+state.price;
        },
        todoDones(state){  //所有已完成的任務
            return state.todos.filter(p=>p.done);
        },
        todoDonesLength(state,getters){  //返回已完成項的個數
            return getters.todoDones.length;
        },
        findTask:(state)=>(id)=>{  //根據編號獲得任務項
            return state.todos.find(p=>p.id==id);
        }
    },
    //變更,相當於method,更新方法
    mutations:{
        increment(state,n){
            state.count+=n;
        }
    }
});

CounterA.vue

<template>
  <div class="counter">
    <h2>計數器A</h2>
    <h3>方法一:{{ $store.getters.countAndPrice }}</h3>
    <h3>方法二:{{ store.getters.countAndPrice }}</h3>
    <h3>方法三:{{ cAndp }}</h3>
    <h3>todoDones:{{ store.getters.todoDones }}</h3>
    <h3>todoDonesLength:{{ store.getters.todoDonesLength }}</h3>
    <h3>findTask:{{ store.getters.findTask(2) }}</h3>
    <hr />
    <h3>todoDones:{{ todoDones }}</h3>
    <h3>todoDonesLength:{{ todoDonesLength }}</h3>
  </div>
</template>
<script lang="ts">
import { useStore, mapGetters } from "vuex";
export default {
  setup() {
    const store = useStore();
    return { store };
  },
  computed: {
    cAndp(this: any) {
      return this.$store.getters.countAndPrice;
    },
    ...mapGetters(["todoDones", "todoDonesLength"]),
  },
};
</script>
<style scoped>
.counter {
  background: #def;
}
</style>

運行結果:

2.6、mutation 更新

mutation:提交更新數據的方法,必須是同步的(異步邏輯在action中寫)

2.6.1、Mutation

更改 Vuex 的 store 中的狀態的唯一方法是提交 mutation。Vuex 中的 mutation 非常類似於事件:每個 mutation 都有一個字符串的事件類型 (type)和一個回調函數 (handler)。這個回調函數就是我們實際進行狀態更改的地方,並且它會接受 state 作爲第一個參數:

const store = createStore({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 變更狀態
      state.count++
    }
  }
})

你不能直接調用一個 mutation 處理函數。這個選項更像是事件註冊:“當觸發一個類型爲 increment 的 mutation 時,調用此函數。”要喚醒一個 mutation 處理函數,你需要以相應的 type 調用 store.commit 方法:

store.commit('increment')

2.6.2、提交載荷(Payload)

你可以向 store.commit 傳入額外的參數,即 mutation 的載荷(payload):

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)

在大多數情況下,載荷應該是一個對象,這樣可以包含多個字段並且記錄的 mutation 會更易讀:

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10
})

2.6.3、對象風格的提交方式

提交 mutation 的另一種方式是直接使用包含 type 屬性的對象:

store.commit({
  type: 'increment',
  amount: 10
})

當使用對象風格的提交方式,整個對象都作爲載荷傳給 mutation 函數,因此處理函數保持不變:

mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}

2.6.4、使用常量替代 Mutation 事件類型

使用常量替代 mutation 事件類型在各種 Flux 實現中是很常見的模式。這樣可以使 linter 之類的工具發揮作用,同時把這些常量放在單獨的文件中可以讓你的代碼合作者對整個 app 包含的 mutation 一目瞭然:

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import { createStore } from 'vuex'
import { SOME_MUTATION } from './mutation-types'

const store = createStore({
  state: { ... },
  mutations: {
    // 我們可以使用 ES2015 風格的計算屬性命名功能
    // 來使用一個常量作爲函數名
    [SOME_MUTATION] (state) {
      // 修改 state
    }
  }
})

用不用常量取決於你——在需要多人協作的大型項目中,這會很有幫助。但如果你不喜歡,你完全可以不這樣做。

2.6.5、Mutation 必須是同步函數

一條重要的原則就是要記住 mutation 必須是同步函數。爲什麼?請參考下面的例子:

mutations: {
  someMutation (state) {
    api.callAsyncMethod(() => {
      state.count++
    })
  }
}

現在想象,我們正在 debug 一個 app 並且觀察 devtool 中的 mutation 日誌。每一條 mutation 被記錄,devtools 都需要捕捉到前一狀態和後一狀態的快照。然而,在上面的例子中 mutation 中的異步函數中的回調讓這不可能完成:因爲當 mutation 觸發的時候,回調函數還沒有被調用,devtools 不知道什麼時候回調函數實際上被調用——實質上任何在回調函數中進行的狀態的改變都是不可追蹤的。

2.6.6、在組件中提交 Mutation

你可以在組件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 輔助函數將組件中的 methods 映射爲 store.commit 調用(需要在根節點注入 store)。

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 將 `this.increment()` 映射爲 `this.$store.commit('increment')`

      // `mapMutations` 也支持載荷:
      'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 將 `this.add()` 映射爲 `this.$store.commit('increment')`
    })
  }
}

<template>
  <button @click="increment({ amount: 10 })">{{ $store.state.count }}</button>
</template>
<script lang="ts">
import { mapMutations } from "vuex";

export default {
  methods: {
    ...mapMutations(["increment", "getOne"]),
  },
};
</script>
<style scoped>
.container {
  background: #def;
}
</style>

2.6.7、下一步:Action

在 mutation 中混合異步調用會導致你的程序很難調試。例如,當你調用了兩個包含異步回調的 mutation 來改變狀態,你怎麼知道什麼時候回調和哪個先回調呢?這就是爲什麼我們要區分這兩個概念。在 Vuex 中,mutation 都是同步事務:

store.commit('increment')
// 任何由 "increment" 導致的狀態變更都應該在此刻完成。

2.7、action 動作

action:Action 提交的是 mutation,而不是直接變更狀態;Action 可以任意異步操作。

2.7.1、Action

Action 類似於 mutation,不同在於:

  • Action 提交的是 mutation,而不是直接變更狀態。
  • Action 可以包含任意異步操作。

讓我們來註冊一個簡單的 action:

const store = createStore({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

Action 函數接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調用 context.commit 提交一個 mutation,或者通過 context.state 和 context.getters 來獲取 state 和 getters。當我們在之後介紹到 Modules 時,你就知道 context 對象爲什麼不是 store 實例本身了。

實踐中,我們會經常用到 ES2015 的參數解構來簡化代碼(特別是我們需要調用 commit 很多次的時候):

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

2.7.2、分發 Action

Action 通過 store.dispatch 方法觸發:

store.dispatch('increment')

乍一眼看上去感覺多此一舉,我們直接分發 mutation 豈不更方便?實際上並非如此,還記得 mutation 必須同步執行這個限制麼?Action 就不受約束!我們可以在 action 內部執行異步操作:

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

Actions 支持同樣的載荷方式和對象方式進行分發:

// 以載荷形式分發
store.dispatch('incrementAsync', {
  amount: 10
})

// 以對象形式分發
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

來看一個更加實際的購物車示例,涉及到調用異步 API 和分發多重 mutation:

actions: {
  checkout ({ commit, state }, products) {
    // 把當前購物車的物品備份起來
    const savedCartItems = [...state.cart.added]
    // 發出結賬請求
    // 然後樂觀地清空購物車
    commit(types.CHECKOUT_REQUEST)
    // 購物 API 接受一個成功回調和一個失敗回調
    shop.buyProducts(
      products,
      // 成功操作
      () => commit(types.CHECKOUT_SUCCESS),
      // 失敗操作
      () => commit(types.CHECKOUT_FAILURE, savedCartItems)
    )
  }
}

注意我們正在進行一系列的異步操作,並且通過提交 mutation 來記錄 action 產生的副作用(即狀態變更)。

2.7.3、在組件中分發 Action

你在組件中使用 this.$store.dispatch('xxx') 分發 action,或者使用 mapActions 輔助函數將組件的 methods 映射爲 store.dispatch 調用(需要先在根節點注入 store):

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 將 `this.increment()` 映射爲 `this.$store.dispatch('increment')`

      // `mapActions` 也支持載荷:
      'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 將 `this.add()` 映射爲 `this.$store.dispatch('increment')`
    })
  }
}

2.7.4、組合 Action

Action 通常是異步的,那麼如何知道 action 什麼時候結束呢?更重要的是,我們如何才能組合多個 action,以處理更加複雜的異步流程?

首先,你需要明白 store.dispatch 可以處理被觸發的 action 的處理函數返回的 Promise,並且 store.dispatch 仍舊返回 Promise:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

現在你可以:

store.dispatch('actionA').then(() => {
  // ...
})

在另外一個 action 中也可以:

actions: {
  // ...
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

最後,如果我們利用 async / await,我們可以如下組合 action:

// 假設 getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

一個 store.dispatch 在不同模塊中可以觸發多個 action 函數。在這種情況下,只有當所有觸發函數完成後,返回的 Promise 纔會執行。

2.8、modules 模塊

modules:聲明子模塊,每一個子模塊擁有自己的state、mutation、action、getters。

2.8.1、Module

由於使用單一狀態樹,應用的所有狀態會集中到一個比較大的對象。當應用變得非常複雜時,store 對象就有可能變得相當臃腫。

爲了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割:

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = createStore({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的狀態
store.state.b // -> moduleB 的狀態

import {createStore} from 'vuex'

const M1={
    namespaced:true,
    state:{
        a:100
    },
    getters:{
        doubleA(state){
            return state.a*2;
        }
    },
    mutations:{
        add(state){
            state.a+=10;
        }
    },
    actions:{
        add({commit}){
            commit("add");
        }
    }
}

const M2={
    namespaced:true,
    state:{
        b:200
    },
    getters:{
        doubleB(state){
            return state.b*2;
        }
    },
    mutations:{
        plus(state){
            state.b+=20;
        }
    },
    actions:{
        plus({commit}){
            commit("plus");
        }
    }
}


export default createStore({
    //數據
    state:{
        count:100
    },
    mutations:{
        increment(state,payload){
            return state.count+=payload.amount;
        },
        getOne(){
            return "one";
        }
    },
    actions:{
        async increment({commit},payload){
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                   let result=commit("increment",payload);
                    resolve(result);
                }, 2000);
            });
        }
    },
    modules:{
        M1,M2
    }
});

CountA.vue

<template>
  <button @click="add({ amount: 200 })">{{ store.state.count }}</button>
  <hr />
  <button @click="store.dispatch('M1/add')">
    store.state.M1.a={{ store.state.M1.a }}
  </button>
  <hr />
  <button @click="store.dispatch('M2/plus')">
    store.state.M2.b={{ store.state.M2.b }}
  </button>
</template>
<script lang="ts">
import { useStore } from "vuex";

export default {
  setup() {
    const store = useStore();
    function add(payload) {
      store
        .dispatch({
          type: "increment",
          amount: 200,
        })
        .then((p) => {
          alert(p);
        });
    }
    return { store, add };
  },
  methods: {},
};
</script>
<style scoped>
.container {
  background: #def;
}
</style>

2.8.2、模塊的局部狀態

對於模塊內部的 mutation 和 getter,接收的第一個參數是模塊的局部狀態對象。

const moduleA = {
  state: () => ({
    count: 0
  }),
  mutations: {
    increment (state) {
      // 這裏的 `state` 對象是模塊的局部狀態
      state.count++
    }
  },
  getters: {
    doubleCount (state) {
      return state.count * 2
    }
  }
}

同樣,對於模塊內部的 action,局部狀態通過 context.state 暴露出來,根節點狀態則爲 context.rootState

const moduleA = {
  // ...
  actions: {
    incrementIfOddOnRootSum ({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }
}

對於模塊內部的 getter,根節點狀態會作爲第三個參數暴露出來:

const moduleA = {
  // ...
  getters: {
    sumWithRootCount (state, getters, rootState) {
      return state.count + rootState.count
    }
  }
}

2.8.3、命名空間

默認情況下,模塊內部的 action 和 mutation 仍然是註冊在全局命名空間的——這樣使得多個模塊能夠對同一個 action 或 mutation 作出響應。Getter 同樣也默認註冊在全局命名空間,但是目前這並非出於功能上的目的(僅僅是維持現狀來避免非兼容性變更)。必須注意,不要在不同的、無命名空間的模塊中定義兩個相同的 getter 從而導致錯誤。

如果希望你的模塊具有更高的封裝度和複用性,你可以通過添加 namespaced: true 的方式使其成爲帶命名空間的模塊。當模塊被註冊後,它的所有 getter、action 及 mutation 都會自動根據模塊註冊的路徑調整命名。例如:

const store = createStore({
  modules: {
    account: {
      namespaced: true,

      // 模塊內容(module assets)
      state: () => ({ ... }), // 模塊內的狀態已經是嵌套的了,使用 `namespaced` 屬性不會對其產生影響
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },

      // 嵌套模塊
      modules: {
        // 繼承父模塊的命名空間
        myPage: {
          state: () => ({ ... }),
          getters: {
            profile () { ... } // -> getters['account/profile']
          }
        },

        // 進一步嵌套命名空間
        posts: {
          namespaced: true,

          state: () => ({ ... }),
          getters: {
            popular () { ... } // -> getters['account/posts/popular']
          }
        }
      }
    }
  }
})

啓用了命名空間的 getter 和 action 會收到局部化的 getterdispatch 和 commit。換言之,你在使用模塊內容(module assets)時不需要在同一模塊內額外添加空間名前綴。更改 namespaced 屬性後不需要修改模塊內的代碼。

在帶命名空間的模塊內訪問全局內容(Global Assets)

如果你希望使用全局 state 和 getter,rootState 和 rootGetters 會作爲第三和第四參數傳入 getter,也會通過 context 對象的屬性傳入 action。

若需要在全局命名空間內分發 action 或提交 mutation,將 { root: true } 作爲第三參數傳給 dispatch 或 commit 即可。

modules: {
  foo: {
    namespaced: true,

    getters: {
      // 在這個模塊的 getter 中,`getters` 被局部化了
      // 你可以使用 getter 的第四個參數來調用 `rootGetters`
      someGetter (state, getters, rootState, rootGetters) {
        getters.someOtherGetter // -> 'foo/someOtherGetter'
        rootGetters.someOtherGetter // -> 'someOtherGetter'
        rootGetters['bar/someOtherGetter'] // -> 'bar/someOtherGetter'
      },
      someOtherGetter: state => { ... }
    },

    actions: {
      // 在這個模塊中, dispatch 和 commit 也被局部化了
      // 他們可以接受 `root` 屬性以訪問根 dispatch 或 commit
      someAction ({ dispatch, commit, getters, rootGetters }) {
        getters.someGetter // -> 'foo/someGetter'
        rootGetters.someGetter // -> 'someGetter'
        rootGetters['bar/someGetter'] // -> 'bar/someGetter'

        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

        commit('someMutation') // -> 'foo/someMutation'
        commit('someMutation', null, { root: true }) // -> 'someMutation'
      },
      someOtherAction (ctx, payload) { ... }
    }
  }
}

在帶命名空間的模塊註冊全局 action

若需要在帶命名空間的模塊註冊全局 action,你可添加 root: true,並將這個 action 的定義放在函數 handler 中。例如:

{
  actions: {
    someOtherAction ({dispatch}) {
      dispatch('someAction')
    }
  },
  modules: {
    foo: {
      namespaced: true,

      actions: {
        someAction: {
          root: true,
          handler (namespacedContext, payload) { ... } // -> 'someAction'
        }
      }
    }
  }
}

帶命名空間的綁定函數

當使用 mapStatemapGettersmapActions 和 mapMutations 這些函數來綁定帶命名空間的模塊時,寫起來可能比較繁瑣:

computed: {
  ...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  }),
  ...mapGetters([
    'some/nested/module/someGetter', // -> this['some/nested/module/someGetter']
    'some/nested/module/someOtherGetter', // -> this['some/nested/module/someOtherGetter']
  ])
},
methods: {
  ...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    'some/nested/module/bar' // -> this['some/nested/module/bar']()
  ])
}

對於這種情況,你可以將模塊的空間名稱字符串作爲第一個參數傳遞給上述函數,這樣所有綁定都會自動將該模塊作爲上下文。於是上面的例子可以簡化爲:

computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  }),
  ...mapGetters('some/nested/module', [
    'someGetter', // -> this.someGetter
    'someOtherGetter', // -> this.someOtherGetter
  ])
},
methods: {
  ...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
  ])
}

而且,你可以通過使用 createNamespacedHelpers 創建基於某個命名空間輔助函數。它返回一個對象,對象裏有新的綁定在給定命名空間值上的組件綁定輔助函數:

import { createNamespacedHelpers } from 'vuex'

const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')

export default {
  computed: {
    // 在 `some/nested/module` 中查找
    ...mapState({
      a: state => state.a,
      b: state => state.b
    })
  },
  methods: {
    // 在 `some/nested/module` 中查找
    ...mapActions([
      'foo',
      'bar'
    ])
  }
}

給插件開發者的注意事項

如果你開發的插件(Plugin)提供了模塊並允許用戶將其添加到 Vuex store,可能需要考慮模塊的空間名稱問題。對於這種情況,你可以通過插件的參數對象來允許用戶指定空間名稱:

// 通過插件的參數對象得到空間名稱
// 然後返回 Vuex 插件函數
export function createPlugin (options = {}) {
  return function (store) {
    // 把空間名字添加到插件模塊的類型(type)中去
    const namespace = options.namespace || ''
    store.dispatch(namespace + 'pluginAction')
  }
}

2.8.4、模塊動態註冊

在 store 創建之後,你可以使用 store.registerModule 方法註冊模塊:

import { createStore } from 'vuex'

const store = createStore({ /* 選項 */ })

// 註冊模塊 `myModule`
store.registerModule('myModule', {
  // ...
})

// 註冊嵌套模塊 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
  // ...
})

之後就可以通過 store.state.myModule 和 store.state.nested.myModule 訪問模塊的狀態。

模塊動態註冊功能使得其他 Vue 插件可以通過在 store 中附加新模塊的方式來使用 Vuex 管理狀態。例如,vuex-router-sync 插件就是通過動態註冊模塊將 Vue Router 和 Vuex 結合在一起,實現應用的路由狀態管理。

你也可以使用 store.unregisterModule(moduleName) 來動態卸載模塊。注意,你不能使用此方法卸載靜態模塊(即創建 store 時聲明的模塊)。

注意,你可以通過 store.hasModule(moduleName) 方法檢查該模塊是否已經被註冊到 store。需要記住的是,嵌套模塊應該以數組形式傳遞給 registerModule 和 hasModule,而不是以路徑字符串的形式傳遞給 module。

保留 state

在註冊一個新 module 時,你很有可能想保留過去的 state,例如從一個服務端渲染的應用保留 state。你可以通過 preserveState 選項將其歸檔:store.registerModule('a', module, { preserveState: true })

當你設置 preserveState: true 時,該模塊會被註冊,action、mutation 和 getter 會被添加到 store 中,但是 state 不會。這裏假設 store 的 state 已經包含了這個 module 的 state 並且你不希望將其覆寫。

2.8.5、模塊重用

有時我們可能需要創建一個模塊的多個實例,例如:

如果我們使用一個純對象來聲明模塊的狀態,那麼這個狀態對象會通過引用被共享,導致狀態對象被修改時 store 或模塊間數據互相污染的問題。

實際上這和 Vue 組件內的 data 是同樣的問題。因此解決辦法也是相同的——使用一個函數來聲明模塊狀態(僅 2.3.0+ 支持):

const MyReusableModule = {
  state: () => ({
    foo: 'bar'
  }),
  // mutation、action 和 getter 等等...
}

三、Pinia

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章