以下內(nèi)容是引用或者借鑒別人的,自己只是做個(gè)筆記,方便學(xué)習(xí)。理解錯(cuò)誤的地方,歡迎評論。如有侵權(quán),私聊我刪除,未經(jīng)允許,不準(zhǔn)作為商業(yè)用途
實(shí)現(xiàn)vuex.Store,接受一個(gè)對象參數(shù),主要包含state,actions,mutations,getters等
- 核心,用new Vue創(chuàng)建一個(gè)數(shù)據(jù)雙向的state
function Store(options) {
this.mutations = options.mutations;
this.actions = options.actions;
this.state = options.state;
//雙向綁定
var state = options.state;
var store = this;
function resetStoreVM(store, state) {
store._vm = new Vue({
data: {
$$state: state
}
});
}
resetStoreVM(store, state);
//獲取值getters
let getters = options.getters || {}
this.getters = {}
Object.keys(getters).forEach(getterName=>{
Object.defineProperty(this.getters,getterName,{
get:()=>{
return getters[getterName](this.state)
}
})
})
// 觸發(fā)更新dispatch
this.dispatch = function (type, payload) {
store.actions[type]({ commit: store.commit, state: store.state }, payload);
};
// 觸發(fā)更新commit
this.commit = function (type, payload) {
store.mutations[type](store.state, payload)
// store.state.userInfo = payload
};
// 實(shí)現(xiàn)獲取state的值
// get state(){
// return this._vm.data.$$state
// }
}
// 實(shí)現(xiàn)獲取state的值
var prototypeAccessors$1 = { state: { configurable: true } };
prototypeAccessors$1.state.get = function () {
return this._vm._data.$$state
};
prototypeAccessors$1.state.set = function (v) {};
Object.defineProperties( Store.prototype, prototypeAccessors$1 );
- 創(chuàng)建實(shí)例
new Vuex.Store({
state: {
// 登錄賬戶信息
userInfo: sessionStorage.getItem('userInfo') ? JSON.parse(sessionStorage.getItem('userInfo')) : '1',
// 選擇的學(xué)校信息
schoolInfo: sessionStorage.getItem('schoolInfo') ? JSON.parse(sessionStorage.getItem('schoolInfo')) : '2'
},
actions: {
setUserInfoActions({
commit
}, data) {
commit('setUserInfoMutations', data)
},
setSchoolInfoActions({
commit
}, data) {
commit('setSchoolInfoMutations', data)
},
},
mutations: {
setUserInfoMutations(state, data) {
state.userInfo = data
sessionStorage.setItem('userInfo', JSON.stringify(data))
},
setSchoolInfoMutations(state, data) {
// data.schoolId = 4403050134;
state.schoolInfo = Object.assign({}, data)
sessionStorage.setItem('schoolInfo', JSON.stringify(data))
},
loginOutMutations(state) {
state.userInfo = ''
state.schoolInfo = ''
sessionStorage.removeItem('userInfo')
sessionStorage.removeItem('schoolInfo')
}
},
getters: {
userInfo: state => state.userInfo,
schoolInfo: state => state.schoolInfo,
}
})
實(shí)現(xiàn)將store對象綁定到每一個(gè)組件實(shí)例上面
- 核心,利用Vue.mixin()將它混入每一個(gè)組件
function install(Vue) {
Vue.mixin({ beforeCreate: vuexInit });
function vuexInit() {
var options = this.$options;
if (options.store) {
this.$store = typeof options.store === 'function'
? options.store()
: options.store;
} else if (options.parent && options.parent.$store) {
this.$store = options.parent.$store;
}
}
}
導(dǎo)出
var index = {
Store: Store,
install: install,
version: '3.1.2',
}
export default index