Vuex之理解Store

理解Store

1.什麼是Storevue

  • 上一篇文章說了,Vuex就是提供一個倉庫,Store倉庫裏面放了不少對象。其中state就是數據源存放地,對應於與通常Vue對象裏面的data(後面講到的actionsmutations對應於methods)。vuex

  • 在使用Vuex的時候一般會建立Store實例new Vuex.store({state,getters,mutations,actions})有不少子模塊的時候還會使用到modulessegmentfault

  • clipboard.png

  • 總結,Store類就是存儲數據和管理數據方法的倉庫,實現方式是將數據和方法已對象形式傳入其實例中。要注意一個應用或是項目中只能存在一個Store實例!!promise


2.Store源碼分析app

class Store{
     constructor (options = {}) {
     1.部分2個‘斷言函數’判斷條件
     assert(Vue, `must call Vue.use(Vuex) before creating a store 
     instance.`)  // 在Store實例化以前必定要確保Vue的存在
     assert(typeof Promise !== 'undefined', `vuex requires a Promise polyfill in this browser.`)
     //確保promise存在
     
     2.結構賦值拿到options裏面的state,plugins和strict
     const {
        state = {},   //rootState
        plugins = [], // 插件
        strict = false //是否嚴格模式
            } = options
            
     3.Store internal state建立store內部屬性
     this._options = options //存儲參數
     this._committing = false //標識提交狀態,保證修改state只能在mutation裏面,不能在外部隨意修改
     this._actions = Object.create(null)  //存儲用戶定義的actions
     this._mutations = Object.create(null) //存儲用戶定義的mutations
     this._wrappedGetters = Object.create(null) //存儲用戶定義的getters
     this._runtimeModules = Object.create(null) //存儲運行時的modules
     this._subscribers = []   //存儲全部堵mutation變化的訂閱者
     this._watcherVM = new Vue() //借用Vue實例的方法,$watch來觀測變化
     
     4.將dispatch和commit的this指向當前store實例
     const store = this
     const { dispatch, commit } = this
     this.dispatch = function boundDispatch (type, payload) {
     return dispatch.call(store, type, payload)}
     this.commit = function boundCommit (type, payload, options) {
     return commit.call(store, type, payload, options)}}

後面文章逐步分析每個模塊。函數

相關文章
相關標籤/搜索