一、 Getter
我們先回憶一下上一篇的代碼
computed:{  getName(){   return this.$store.state.name  }}這里假設現在邏輯有變,我們最終期望得到的數據(getName),是基于 this.$store.state.name 上經過復雜計算得來的,剛好這個getName要在好多個地方使用,那么我們就得復制好幾份.
vuex 給我們提供了 getter,請看代碼 (文件位置 /src/store/index.js)
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({ // 類似 vue 的 data state: {  name: 'oldName' }, // 類似 vue 的 computed -----------------以下5行為新增 getters:{  getReverseName: state => {    return state.name.split('').reverse().join('')  } }, // 類似 vue 里的 mothods(同步方法) mutations: {  updateName (state) {   state.name = 'newName'  } }})然后我們可以這樣用 文件位置 /src/main.js
computed:{  getName(){   return this.$store.getters.getReverseName  }}事實上, getter 不止單單起到封裝的作用,它還跟vue的computed屬性一樣,會緩存結果數據, 只有當依賴改變的時候,才要重新計算.
二、 actions和$dispatch
細心的你,一定發現我之前代碼里 mutations 頭上的注釋了 類似 vue 里的 mothods(同步方法)
為什么要在 methods 后面備注是同步方法呢? mutation只能是同步的函數,只能是同步的函數,只能是同步的函數!! 請看vuex的解釋:
現在想象,我們正在 debug 一個 app 并且觀察 devtool 中的 mutation 日志。每一條 mutation 被記錄, devtools 都需要捕捉到前一狀態和后一狀態的快照。然而,在上面的例子中 mutation 中的異步函數中的回調讓這不 可能完成:因為當 mutation 觸發的時候,回調函數還沒有被調用,devtools 不知道什么時候回調函數實際上被調 用——實質上任何在回調函數中進行的狀態的改變都是不可追蹤的。
那么如果我們想觸發一個異步的操作呢? 答案是: action + $dispatch, 我們繼續修改store/index.js下面的代碼
文件位置 /src/store/index.js
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({ // 類似 vue 的 data state: {  name: 'oldName' }, // 類似 vue 的 computed getters:{  getReverseName: state => {    return state.name.split('').reverse().join('')  } }, // 類似 vue 里的 mothods(同步方法) mutations: {  updateName (state) {   state.name = 'newName'  } }, // 類似 vue 里的 mothods(異步方法) -------- 以下7行為新增 actions: {  updateNameAsync ({ commit }) {   setTimeout(() => {    commit('updateName')   }, 1000)  } }})然后我們可以再我們的vue頁面里面這樣使用
methods: {  rename () {    this.$store.dispatch('updateNameAsync')  }}            
新聞熱點
疑難解答
圖片精選