Vuex之理解Store的用法,vuexstore用法
1.什麼是Store?
上一篇文章說了,Vuex就是提供一個倉庫,Store倉庫裡面放了很多個物件。其中state就是資料來源存放地,對應於與一般Vue對象裡面的data(後面講到的actions和mutations對應於methods)。
在使用Vuex的時候通常會建立Store執行個體new Vuex.store({state,getters,mutations,actions})有很多子模組的時候還會使用到modules。
總結,Store類就是儲存資料和管理資料方法的倉庫,實現方式是將資料和方法已對象形式傳入其執行個體中。要注意一個應用或是項目中只能存在一個Store執行個體!!
2.Store源碼分析
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 //是否strict 模式 } = 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)}}
後面文章逐步分析每一個模組。
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。