Vuex之理解Store的用法
1.什么是Store?
上一篇文章說了,Vuex
就是提供一個倉庫,Store
倉庫里面放了很多對象。其中state就是數(shù)據(jù)源存放地,對應于與一般Vue
對象里面的data
(后面講到的actions
和mutations
對應于methods
)。
在使用Vuex
的時候通常會創(chuàng)建Store
實例new Vuex.store({state,getters,mutations,actions})
有很多子模塊的時候還會使用到modules
。
總結(jié),Store
類就是存儲數(shù)據(jù)和管理數(shù)據(jù)方法的倉庫,實現(xiàn)方式是將數(shù)據(jù)和方法已對象形式傳入其實例中。要注意一個應用或是項目中只能存在一個Store
實例??!
2.Store源碼分析
class Store{ constructor (options = {}) { // 1.部分2個‘斷言函數(shù)'判斷條件 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.結(jié)構(gòu)賦值拿到options里面的state,plugins和strict const { state = {}, //rootState plugins = [], // 插件 strict = false //是否嚴格模式 } = options // 3.Store internal state創(chuàng)建store內(nèi)部屬性 this._options = options //存儲參數(shù) this._committing = false //標識提交狀態(tài),保證修改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)}}
后面文章逐步分析每一個模塊。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue+FormData+axios實現(xiàn)圖片上傳功能的項目實戰(zhàn)
本文主要介紹了Vue+FormData+axios實現(xiàn)圖片上傳功能的項目實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06一步步教你利用webpack如何搭一個vue腳手架(超詳細講解和注釋)
這篇文章主要給大家介紹了軟玉利用webpack如何搭一個vue腳手架的相關資料,文中有超詳細講解和注釋,對大家學習或者使用webpack具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2018-01-01