vue(23)Vuex的5個核心概念

Vuex的核心概念

Vuex有5個核心概念,分別是StateGettersmutationsActionsModules
 vue

State

  Vuex使用單一狀態樹,也就是說,用一個對象包含了全部應用層級的狀態,做爲惟一數據源而存在。沒一個Vuex應用的核心就是storestore可理解爲保存應用程序狀態的容器。store與普通的全局對象的區別有如下兩點:
  (1)Vuex的狀態存儲是響應式的。當Vue組件從store中檢索狀態的時候,若是store中的狀態發生變化,那麼組件也會相應地獲得高效更新。
  (2)不能直接改變store中的狀態。改變store中的狀態的惟一途徑就是顯式地提交mutation。這能夠確保每一個狀態更改都留下可跟蹤的記錄,從而可以啓用一些工具來幫助咱們更好的理解應用
  安裝好Vuex以後,就能夠開始建立一個store,代碼以下:node

const store =  new Vuex.Store({
  // 狀態數據放到state選項中
  state: {
    counter: 1000,
  },
  // mutations選項中定義修改狀態的方法
  // 這些方法接收state做爲第1個參數
  mutations: {
    increment(state) {
      state.counter++;
    },
  },
});

  在組件中訪問store的數據,能夠直接使用store.state.count。在模塊化構建系統中,爲了方便在各個單文件組件中訪問到store,應該在Vue根實例中使用store選項註冊store實例,該store實例會被注入根組件下的所偶遇子組件中,在子組件中就能夠經過this.$store來訪問store。代碼以下:vuex

new Vue({
  el: "#app",
  store,
})

  若是在組件中要展現store中的狀態,應該使用計算屬性來返回store的狀態,代碼以下:數組

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

  以後在組件的模板中就能夠直接使用count。當storecount發生改變時,組件內的計算屬性count也會同步發生改變。
  那麼如何更改store中的狀態呢?注意不要直接去修改count的值,例如:緩存

methods: {
    handleClick(){
        this.&store.state.count++;    // 不要這麼作
    }
}

  既然選擇了Vuex做爲你的應用的狀態管理方案,那麼就應該遵守Vuex的要求;經過提交mutation來更改store中的狀態。在嚴格模式下,若是store中的狀態改變不是有mutation函數引發的,則會拋出錯誤,並且若是直接修改store中的狀態,Vue的調試工具也沒法跟蹤狀態的改變。在開發階段,能夠開啓嚴格模式,以免字節的狀態修改,在建立store的時候,傳入strict: true代碼以下:app

const store = new Vuex.Store({
    strict: true
})

  Vuex中的mutation很是相似於事件:每一個mutation都有一個字符串的事件類型和一個處理器函數,這個處理器函數就是實際進行狀態更改的地方,它接收state做爲第1個參數。
  咱們不能直接調用一個mutation處理器函數,mutations選項更像是事件註冊,當觸發一個類型爲incrementmutation時,調用此函數。要調用一個mutation處理器函數,須要它的類型去調用store.commit方法,代碼以下:異步

store.commit("increment")

 

Getters

  假如在store的狀態中定義了一個圖書數組,代碼以下:async

export default new Vuex.Store({
  state: {
    books: [
      { id: 1, title: "Vue.js", isSold: false },
      { id: 2, title: "common.js", isSold: true },
      { id: 3, title: "node.js", isSold: true },
    ],
  },
})

  在組件內須要獲得正在銷售的書,因而定義一個計算屬性sellingBooks,對state中的books進行過濾,代碼以下:ide

computed: {
    sellingBooks(){
        return this.$store.state.books.filter(book => book.isSold === true);
    }
}

  這沒有什麼問題,但若是是多個組件都須要用到sellingBooks屬性,那麼應該怎麼辦呢?是複製代碼,仍是抽取爲共享函數在多處導入?顯然,這都不理想
  Vuex容許咱們在store中定義getters(能夠認爲是store的計算屬性)。與計算屬性同樣,getter的返回值會根據它的依賴項被緩存起來,且只有在它的依賴項發生改變時纔會從新計算。
  getter接收state做爲其第1個參數,代碼以下:模塊化

export default new Vuex.Store({
  state: {
    books: [
      { id: 1, title: "Vue.js", isSold: false },
      { id: 2, title: "common.js", isSold: true },
      { id: 3, title: "node.js", isSold: true },
    ],
  },
  getters: {
    sellingBooks(state) {
      return state.books.filter((b) => b.isSold === true);
    },
  }
})

  咱們定義的getter將做爲store.getters對象的豎向來訪問,代碼以下;

<h3>{{ $store.getters.sellingBooks }}</h3>

getter也能夠接收其餘getter做爲第2個參數,代碼以下:

getters: {
    sellingBooks(state) {
      return state.books.filter((b) => b.isSold === true);
    },
    sellingBooksCount(state, getters) {
      return getters.sellingBooks.length;
    },
}

  在組件內,要簡化getter的調用,一樣可使用計算屬性,代碼以下:

computed: {
    sellingBooks() {
      return this.$store.getters.sellingBooks;
    },
    sellingBooksCount() {
      return this.$store.getters.sellingBooksCount;
    },
  },

  要注意,做爲屬性訪問的getter做爲Vue的響應式系統的一部分被緩存。
  若是想簡化上述getter在計算屬性中的訪問形式,可使用mapGetters輔助函數。mapGetters 輔助函數僅僅是將 store 中的 getter 映射到局部計算屬性:

import { mapGetters } from 'vuex'

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

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

...mapGetters({
  // 把 `this.booksCount` 映射爲 `this.$store.getters.sellingBooksCount`
  booksCount: 'sellingBooksCount'
})

  getter還有更靈活的用法,用過讓getter返回一個函數,來實現給getter傳參。例如,下面的getter根據圖書ID來查找圖書對象

getters: {
    getBookById(state) {
      return function (id) {
        return state.books.filter((book) => book.id === id);
      };
    },
}

  若是你對箭頭函數已經掌握的爐火純青,那麼可使用箭頭函數來簡化上述代碼

getters: {
    getBookById(state) {
      return (id) => state.books.filter((book) => book.id === id);
    },

下面在組件模板中的調用返回{ "id": 1, "title": "Vue.js", "isSold": false }

<h3>{{ $store.getters.getBookById(1) }}</h3>

 

mutation

上面已經介紹了更改store中的狀態的惟一方式是提交mutation
 

提交載荷(Payload)

在使用store.commit方法提交mutation時,還能夠傳入額外的參數,即mutation的載荷(payload),代碼以下:

mutations: {
    increment(state, n) {
      state.counter+= n;
    },
  },

store,commit("increment", 10)

載荷也能夠是一個對象,代碼以下:

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

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

 

對象風格的提交方式

提交mutation時,也可使用包含type屬性的對象,這樣傳一個參數就能夠了。代碼以下所示:

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

當使用對象風格提交時,整個對象將做爲載荷還給mutation函數,所以處理器保持不變。代碼以下:

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

在組件中提交mutation時,使用的是this.$store.commit("increment"),若是你以爲這樣比較繁瑣,可使用mapMutations輔助函數將組件中的方法映射爲store.commit調用,代碼以下:

import { mapMutations } from "vuex";
methods: {
    ...mapMutations([
      // 將this.increment()映射爲this.$store.commit("increment")
      "increment",
    ]),
}

除了使用字符串數組外,mapMutations函數的參數也能夠是一個對象

import { mapMutations } from "vuex";
methods: {
    ...mapMutations([
      // 將this.add()映射爲this.$store.commit("increment")
      add: "increment",
    ]),
}

 

Mutation 需遵照 Vue 的響應規則

既然 Vuexstore 中的狀態是響應式的,那麼當咱們變動狀態時,監視狀態的 Vue 組件也會自動更新。這也意味着 Vuex 中的 mutation 也須要與使用 Vue 同樣遵照一些注意事項:

1.最好提早在你的 store 中初始化好全部所需屬性。
2.當須要在對象上添加新屬性時,你應該

  • 使用 Vue.set(obj, 'newProp', 123), 或者
  • 以新對象替換老對象。例如,利用對象展開運算符 (opens new window)咱們能夠這樣寫:
state.obj = { ...state.obj, newProp: 123 }

 

使用常量替代 Mutation 事件類型

咱們可使用常量來替代mutation類型。能夠把常量放到一個單獨的JS文件中,有助於項目團隊對store中所包含的mutation一目瞭然,例如:

// mutation-types.js
export const INCREMENT = "increment";

// store.js
import Vuex from "vuex";
import { INCREMENT } from "./mutation-types";
const store = new Vuex.Store({
  state: { ... },
  mutations: {
    // 咱們可使用 ES2015 風格的計算屬性命名功能來使用一個常量做爲函數名
    [INCREMENT] (state) {
      // mutate 狀態
    }
  }
})

 

Actions

  在定義mutation時,有一個重要的原則就是mutation必須是同步函數,換句話說,在mutation處理器函數中,不能存在異步調用,好比

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      setTimeout( () => {
        state.count++
      }, 2000)
    }
  }
})

  在increment函數中調用setTimeout()方法在2s後更新count,這就是一個異步調用。記住,不要這麼作,由於這會讓調試變得困難。假設正在調試應用程序並查看devtool中的mutation日誌,對於每一個記錄的mutationdevtool都須要捕捉到前一狀態的快照。然而,在上面的例子中,mutation中的setTimeout方法中的回調讓這不可能完成。由於當mutation被提交的時候,回調函數尚未被調用,devtool也沒法知道回調函數何時真正被調用。實際上,任何在回調函數中執行的狀態的改變都是不可追蹤的。
  若是確實須要執行異步操做,那麼應該使用actionaction相似於mutation,不一樣之處在於:

  • action提交的是mutation,而不是直接變動狀態。
  • action能夠包含任意異步操做

一個簡單的action示例以下:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
        state.count++
    }
  },
  actions: {
    increment(context) {
      context.commit("increment");
    },
  },
})

  Action 函數接受一個與 store 實例具備相同方法和屬性的 context 對象,所以你能夠調用 context.commit 提交一個 mutation,或者經過 context.statecontext.getters 來獲取 stategetters。甚至能夠用context.dispatch調用其餘的action。要注意的是,context對象並非store實例自己
  若是在action中須要屢次調用commit,則能夠考慮使用ECMAScript6中的解構語法來簡化代碼,以下所示:

actions: {
    increment({ commit }) {
      commit("increment");
    },
  },

  action經過store.dispatch方法觸發,代碼以下:

actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit("increment");
      }, 2000);
    },
  },

  action一樣支持載荷和對象方式進行分發。代碼以下所示:

// 載荷是一個簡單的值
store.dispatch("incrementAsync", 10)

// 載荷是一個對象
store.dispatch("incrementAsync", {
  amount: 10
})

// 直接傳遞一個對象進行分發
store.dispatch({
  type: "incrementAsync",
  amount: 10
})

  在組件中可使用this.$store.dispatch("xxx")分發action,或者使用mapActions輔助函數將組件的方法映射爲store.dispatch調用,代碼以下:

// store.js
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    },
    incrementBy(state, n){
      state.count += n;
    }
  },
  actions: {
    increment({ commit }) {
      commit("increment");
    },
    incrementBy({ commit }, n) {
      commit("incrementBy", n);
    },
  },
})


// 組件
<template>
  <div id="app">
    <button @click="incrementNumber(10)">+10</button>
  </div>
</template>

import { mapActions } from "vuex";
export default {
  name: "App",
  methods: {
    ...mapActions(["increment", "incrementBy"]),
};

  action一般是異步的,那麼如何知道action什麼時候完成呢?更重要的是,咱們如何才能組合多個action來處理更復雜的異步流程呢?
  首先,要知道是store.dispatch能夠處理被觸發的action的處理函數返回的Promise,而且store.dispatch仍舊返回Promise,例如:

actionA({ commit }) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          commit("increment");
          resolve();
        }, 1000);
      });
    },

如今能夠:

store.dispatch("actionA").then(() => {
...
})

在另一個action中也能夠

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

最後,若是咱們利用 async / await (opens new window),咱們能夠以下組合 action

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

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

 

Module

  因爲使用單一狀態樹,應用的全部狀態會集中到一個比較大的對象。當應用變得很是複雜時,store 對象就有可能變得至關臃腫。
  爲了解決以上問題,Vuex 容許咱們將 store 分割成模塊(module)。每一個模塊擁有本身的 statemutationactiongetter、甚至是嵌套子模塊——從上至下進行一樣方式的分割:

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

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

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

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

 

模塊的局部狀態

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

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
    }
  }
}

 

項目結構

Vuex 並不限制你的代碼結構。可是,它規定了一些須要遵照的規則:
1.應用層級的狀態應該集中到單個 store 對象中。
2.提交 mutation 是更改狀態的惟一方法,而且這個過程是同步的。
3.異步邏輯都應該封裝到 action 裏面。

只要你遵照以上規則,如何組織代碼隨你便。若是你的 store 文件太大,只需將 actionmutationgetter 分割到單獨的文件。

對於大型應用,咱們會但願把 Vuex 相關代碼分割到模塊中。下面是項目結構示例:

└── store
    ├── index.js          # 咱們組裝模塊並導出 store 的地方
    ├── actions.js        # 根級別的 action
    ├── mutations.js      # 根級別的 mutation
    └── modules
        ├── cart.js       # 購物車模塊
        └── products.js   # 產品模塊
相關文章
相關標籤/搜索