Vuex之理解Store的用法
1.什么是Store?
上一篇文章說了,Vuex就是提供一個(gè)倉(cāng)庫(kù),Store倉(cāng)庫(kù)里面放了很多對(duì)象。其中state就是數(shù)據(jù)源存放地,對(duì)應(yīng)于與一般Vue對(duì)象里面的data(后面講到的actions和mutations對(duì)應(yīng)于methods)。
在使用Vuex的時(shí)候通常會(huì)創(chuàng)建Store實(shí)例new Vuex.store({state,getters,mutations,actions})有很多子模塊的時(shí)候還會(huì)使用到modules。

總結(jié),Store類就是存儲(chǔ)數(shù)據(jù)和管理數(shù)據(jù)方法的倉(cāng)庫(kù),實(shí)現(xiàn)方式是將數(shù)據(jù)和方法已對(duì)象形式傳入其實(shí)例中。要注意一個(gè)應(yīng)用或是項(xiàng)目中只能存在一個(gè)Store實(shí)例?。?br />
2.Store源碼分析
class Store{
constructor (options = {}) {
// 1.部分2個(gè)‘?dāng)嘌院瘮?shù)'判斷條件
assert(Vue, `must call Vue.use(Vuex) before creating a store
instance.`) // 在Store實(shí)例化之前一定要確保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 //是否嚴(yán)格模式
} = options
// 3.Store internal state創(chuàng)建store內(nèi)部屬性
this._options = options //存儲(chǔ)參數(shù)
this._committing = false //標(biāo)識(shí)提交狀態(tài),保證修改state只能在mutation里面,不能在外部隨意修改
this._actions = Object.create(null) //存儲(chǔ)用戶定義的actions
this._mutations = Object.create(null) //存儲(chǔ)用戶定義的mutations
this._wrappedGetters = Object.create(null) //存儲(chǔ)用戶定義的getters
this._runtimeModules = Object.create(null) //存儲(chǔ)運(yùn)行時(shí)的modules
this._subscribers = [] //存儲(chǔ)所有堵mutation變化的訂閱者
this._watcherVM = new Vue() //借用Vue實(shí)例的方法,$watch來觀測(cè)變化
// 4.將dispatch和commit的this指向當(dāng)前store實(shí)例
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)}}
后面文章逐步分析每一個(gè)模塊。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
element實(shí)現(xiàn)二級(jí)菜單和頂部導(dǎo)航聯(lián)動(dòng)的示例
本文主要介紹了element實(shí)現(xiàn)二級(jí)菜單和頂部導(dǎo)航聯(lián)動(dòng)的示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
Ant?Design?Vue中的table與pagination的聯(lián)合使用方式
這篇文章主要介紹了Ant?Design?Vue中的table與pagination的聯(lián)合使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
vue-element-admin如何轉(zhuǎn)換成中文
這篇文章主要介紹了vue-element-admin如何轉(zhuǎn)換成中文問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Element中的Cascader(級(jí)聯(lián)列表)動(dòng)態(tài)加載省\市\(zhòng)區(qū)數(shù)據(jù)的方法
這篇文章主要介紹了Element中的Cascader(級(jí)聯(lián)列表)動(dòng)態(tài)加載省\市\(zhòng)區(qū)數(shù)據(jù)的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-03-03
Vue實(shí)現(xiàn)移除數(shù)組中特定元素的方法小結(jié)
這篇文章主要介紹了Vue如何優(yōu)雅地移除數(shù)組中的特定元素,文中介紹了單個(gè)去除和批量去除的操作方法,并通過代碼示例講解的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2024-03-03

