「Vue原始碼學習」你想知道Vuex的實現原理嗎?

Sunshine_Lin發表於2021-12-30
大家好我是林三心,Vuex 是一個專為 Vue.js 應用程式開發的狀態管理模式。它採用集中式儲存管理應用的所有元件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。

image.png

什麼情況下我應該使用 Vuex?

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

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

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

回顧 Vuex 的使用

安裝

Yarn
yarn add vuex
NPM
npm install vuex --save
在一個模組化的打包系統中,您必須顯式地通過 Vue.use() 來安裝 Vuex:
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

註冊store

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

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

new Vue({
  el: '#app',
  store // 註冊
})

State

  1. 普通使用

    const Counter = {
      template: `<div>{{ count }}</div>`,
      computed: {
     count () {
       return this.$store.state.count
     }
      }
    }
    每當 this.$store.state.count 變化的時候, 都會重新求取計算屬性,並且觸發更新相關聯的 DOM。
  2. 輔助函式

    當一個元件需要獲取多個狀態的時候,將這些狀態都宣告為計算屬性會有些重複和冗餘。為了解決這個問題,我們可以使用 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'
    ])
    物件展開運算子
    computed: {
      localComputed () { /* ... */ },
      // 使用物件展開運算子將此物件混入到外部物件中
      ...mapState({
     // ...
      })
    }

Getters

  1. 普通使用

    Getter 接受 state 作為其第一個引數:
    const store = new Vuex.Store({
      state: {
     todos: [
       { id: 1, text: '...', done: true },
       { id: 2, text: '...', done: false }
     ]
      },
      getters: {
     doneTodos: state => {
       return state.todos.filter(todo => todo.done)
     }
      }
    })
    Getter 也可以接受其他 getter 作為第二個引數:
    getters: {
      // ...
      doneTodosCount: (state, getters) => {
     return getters.doneTodos.length
      }
    }
    我們可以很容易地在任何元件中使用它:
    computed: {
      doneTodosCount () {
     return this.$store.getters.doneTodosCount
      }
    }
    注意,getter 在通過屬性訪問時是作為 Vue 的響應式系統的一部分快取其中的。(同理於computed的快取,後面我會專門出一篇文章講一講)
你也可以通過讓 getter 返回一個函式,來實現給 getter 傳參。在你對 store 裡的陣列進行查詢時非常有用。
getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
  1. 輔助函式

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

    Muations

  2. 普通使用

    Vuex 中的 mutation 非常類似於事件:每個 mutation 都有一個字串的 事件型別 (type) 和 一個 回撥函式 (handler)
    const store = new Vuex.Store({
      state: {
     count: 1
      },
      mutations: {
     increment (state, n) { // n為引數,可設定,可不設定,此引數也稱為“載荷”
       // 變更狀態
       state.count++
     }
      }
    })
    // 使用
    this.$store.commit('increment', 10)
  3. 輔助函式

    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')`
     })
      }
    }
    在 mutation 中混合非同步呼叫會導致你的程式很難除錯。例如,當你呼叫了兩個包含非同步回撥的 mutation 來改變狀態,你怎麼知道什麼時候回撥和哪個先回撥呢?這就是為什麼我們要區分這兩個概念。在 Vuex 中,mutation 都是同步事務

    Action

    Action 類似於 mutation,不同在於:

    • Action 提交的是 mutation,而不是直接變更狀態。
    • Action 可以包含任意非同步操作。
    const store = new Vuex.Store({
      state: {
     count: 0
      },
      mutations: {
     increment (state) {
       state.count++
     }
      },
      actions: {
       // Action 函式接受一個與 store 例項具有相同方法和屬性的 context 物件
      incrementAsync (context , n) { // 可傳“載荷” n
        setTimeout(() => {
          context.commit('increment') 
        }, 1000)
       }
      }
    })
    // 執行
    // 以載荷形式分發
    store.dispatch('incrementAsync', {
      amount: 10
    })
    
    // 以物件形式分發
    store.dispatch({
      type: 'incrementAsync',
      amount: 10
    })
  4. 輔助函式

    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')`
     })
      }
    }
  5. 組合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)。每個模組擁有自己的 state、mutation、action、getter、甚至是巢狀子模組——從上至下進行同樣方式的分割:

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 的狀態
對於模組內部的 mutation 和 getter,接收的第一個引數是模組的區域性狀態物件。
const moduleA = {
  state: () => ({
    count: 0
  }),
  mutations: {
    increment (state) {
      // 這裡的 `state` 物件是模組的區域性狀態
      state.count++
    }
  },

  getters: {
    doubleCount (state) {
      // 這裡的 `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原始碼檔案,發現確實很多,我這裡就講我們最常用的部分功能的原始碼吧

其實使用過 Vuex 的同學都知道,我們在頁面或者元件中都是通過this.$store.xxx 來呼叫的,那麼其實,我們只要把你所建立的store物件賦值給頁面或者元件中的$store變數即可

Vuex的原理通俗講就是:利用了全域性混入Mixin,將你所建立的store物件,混入到每一個Vue例項中,那麼全域性混入是什麼呢?舉個例子:

import Vue from 'vue'
// 全域性混入
Vue.mixin({
  created () {
      console.log('我是林三心')
  }
})

// 之後建立的Vue例項,都會輸出'我是林三心'
const a = new Vue({
  // 這裡什麼都沒有,卻能實現輸出'我是林三心'
})
// => "我是林三心"
const b = new Vue({
  // 這裡什麼都沒有,卻能實現輸出'我是林三心'
})
// => "我是林三心"
上面例子看懂的人,就知道了,同理,把console.log('我是林三心')這段程式碼換成一段能做這件事的程式碼:把store賦值給例項的$store屬性,就實現了:

image.png

程式碼實現

目錄

image.png

  1. vuex.js

    // vuex.js
    let Vue;
    
    // install方法設定,是因為Vue.use(xxx)會執行xxx的install方法
    const install = (v) => { // 引數v負責接收vue例項
     Vue = v;
     // 全域性混入
     Vue.mixin({
         beforeCreate() {
             if (this.$options && this.$options.store) {
                 // 根頁面,直接將身上的store賦值給自己的$store,
                 這也解釋了為什麼使用vuex要先把store放到入口檔案main.js裡的根Vue例項裡
                 this.$store = this.$options.store;
             } else {
                 // 除了根頁面以外,將上級的$store賦值給自己的$store
                 this.$store = this.$parent && this.$parent.$store;
             }
         },
     })
    }
    
    // 建立類Store
    class Store {
     constructor(options) { // options接收傳入的store物件
         this.vm = new Vue({
             // 確保state是響應式
             data: {
                 state: options.state
             }
         });
         // getter
         let getters = options.getters || {};
         this.getters = {};
         console.log(Object.keys(this.getters))
         Object.keys(getters).forEach(getterName => {
             Object.defineProperty(this.getters, getterName, {
                 get: () => {
                     return getters[getterName](this.state);
                 }
             })
         })
         // mutation
         let mutations = options.mutations || {};
         this.mutations = {};
         Object.keys(mutations).forEach(mutationName => {
             this.mutations[mutationName] = payload => {
                 mutations[mutationName](this.state, payload);
             }
         })
         // action
         let actions = options.actions || {};
         this.actions = {};
         Object.keys(actions).forEach(actionName => {
             this.actions[actionName] = payload => {
                 actions[actionName](this.state, payload);
             }
         })
     }
     // 獲取state時,直接返回
     get state() {
         return this.vm.state;
     }
     // commit方法,執行mutations的'name'方法
     commit(name, payload) {
         this.mutations[name](payload);
     }
     // dispatch方法,執行actions的'name'方法
     dispatch(name, payload) {
         this.actions[name](payload);
     }
    }
    
    // 把install方法和類Store暴露出去
    export default {
     install,
     Store
    }
  2. index.js

    // index.js
    import Vue from 'vue';
    import vuex from './vuex'; // 引入vuex.js暴露出來的物件
    Vue.use(vuex); // 會執行vuex物件裡的install方法,也就是全域性混入mixin
    
    // 例項一個Store類,並暴露出去
    export default new vuex.Store({
     state: {
         num: 1
     },
     getters: {
         getNum(state) {
             return state.num * 2;
         }
     },
     mutations: { in (state, payload) {
             state.num += payload;
         },
         de(state, payload) {
             state.num -= payload;
         }
     },
     actions: { in (state, payload) {
             setTimeout(() => {
                 state.num += payload;
             }, 2000)
         }
     }
    })
  3. main.js

    // main.js
    import Vue from 'vue';
    import App from './App.vue'
    
    import store from './store/index'; // 引入剛剛的index.js
    
    
    new Vue({
     store, // 把store掛在根例項上
     el: '#app',
     components: {
         App
     },
     template: '<App/>',
    })
    至此,簡單實現了vuex的state,mutations,getter,actions。以後有機會會專門寫一篇實現mudule的
vue是不提倡全域性混入mixin的,甚至連mixin都不倡導使用,別亂用哦!

結語

我是林三心,一個熱心的前端菜鳥程式設計師。如果你上進,喜歡前端,想學習前端,那我們們可以交朋友,一起摸魚哈哈,摸魚群,加我請備註【思否】

image.png

相關文章