vuex進階知識點鞏固

我們先回憶一下上一篇的代碼

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

三、 Module 模塊化

當項目越來越大的時候,單個 store 文件,肯定不是我們想要的, 所以就有了模塊化. 假設 src/store 目錄下有這2個文件

moduleA.js

export default {
  state: { ... },
  getters: { ... },
  mutations: { ... },
  actions: { ... }
}

moduleB.js

export default {
  state: { ... },
  getters: { ... },
  mutations: { ... },
  actions: { ... }
}

那麼我們可以把 index.js 改成這樣

import moduleA from './moduleA'
import moduleB from './moduleB'

export default new Vuex.Store({
 modules: {
   moduleA,
   moduleB
 }
})

這樣我們就可以很輕鬆的把一個store拆分成多個.

四、 總結
•actions 的參數是 store 對象,而 getters 和 mutations 的參數是 state .
•actions 和 mutations 還可以傳第二個參數,具體看vuex官方文檔
•getters/mutations/actions 都有對應的map,如: mapGetters , 具體看vuex官方文檔
•模塊內部如果怕有命名衝突的話,可以使用命名空間, 具體看vuex官方文檔
•vuex 其實跟 vue 非常像,有data(state),methods(mutations,actions),computed(getters),還能模塊化.

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