vuex進階知識點鞏固

1、 Gettervue

咱們先回憶一下上一篇的代碼vuex

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

這裏假設如今邏輯有變,咱們最終指望獲得的數據(getName),是基於 this.$store.state.name 上通過複雜計算得來的,恰好這個getName要在好多個地方使用,那麼咱們就得複製好幾份.緩存

vuex 給咱們提供了 getter,請看代碼 (文件位置 /src/store/index.js)app

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屬性同樣,會緩存結果數據, 只有當依賴改變的時候,纔要從新計算.模塊化

2、 actions和$dispatch函數

細心的你,必定發現我以前代碼裏 mutations 頭上的註釋了 相似 vue 裏的 mothods(同步方法)this

爲何要在 methods 後面備註是同步方法呢? mutation只能是同步的函數,只能是同步的函數,只能是同步的函數!! 請看vuex的解釋:spa

如今想象,咱們正在 debug 一個 app 而且觀察 devtool 中的 mutation 日誌。每一條 mutation 被記錄, devtools 都須要捕捉到前一狀態和後一狀態的快照。然而,在上面的例子中 mutation 中的異步函數中的回調讓這不 可能完成:由於當 mutation 觸發的時候,回調函數尚未被調用,devtools 不知道何時回調函數實際上被調 用——實質上任何在回調函數中進行的狀態的改變都是不可追蹤的。
那麼若是咱們想觸發一個異步的操做呢? 答案是: action + $dispatch, 咱們繼續修改store/index.js下面的代碼debug

文件位置 /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')
  }
}

3、 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拆分紅多個.

4、 總結
•actions 的參數是 store 對象,而 getters 和 mutations 的參數是 state .
•actions 和 mutations 還能夠傳第二個參數,具體看vuex官方文檔
•getters/mutations/actions 都有對應的map,如: mapGetters , 具體看vuex官方文檔
•模塊內部若是怕有命名衝突的話,能夠使用命名空間, 具體看vuex官方文檔
•vuex 其實跟 vue 很是像,有data(state),methods(mutations,actions),computed(getters),還能模塊化.
相關文章
相關標籤/搜索