用150行程式碼實現Vuex 80%的功能
作者: 殷榮檜@騰訊
本文 地址 ,歡迎檢視
本文 github倉庫程式碼地址 ,歡迎star,謝謝。
如果你對自己用少量程式碼實現各個框架感興趣,那下面這些你都可以一看:
目錄:
一.完成最簡單的通過vuex定義全域性變數,在任何一個頁面可以通過this.$store.state.count可以直接使用
二.vuex中的getter方法的實現
三.mutation和commit方法的實現
四.actions和dispatch方法的實現
五.module方法的實現
六.實現:Vue.use(Vuex)
先來看一下用自己實現的的vuex替代真實的vuex的效果,看看能否正常執行,有沒有報錯:

從執行結果來看,執行正常,沒有問題。接下來看看一步一步實現的過程:
一. 完成最簡單的通過vuex定義全域性變數,在任何一個頁面可以通過this.$store.state.count可以直接使用
main.js程式碼如下:
let store = new Vuex.Store({ state: { count: 0 } }, Vue); new Vue({ store, render: h => h(App), }).$mount('#app') 複製程式碼
store.js的程式碼如下:
export class Store { constructor(options = {}, Vue) { this.options = options; Vue.mixin({ beforeCreate: vuexInit }); } get state () { return this.options.state; } } function vuexInit () { const options = this.$options if (options.store) { // 元件內部設定了store,則優先使用元件內部的store this.$store = typeof options.store === 'function' ? options.store() : options.store } else if (options.parent && options.parent.$store) { // 元件內部沒有設定store,則從根App.vue下繼承$store方法 this.$store = options.parent.$store } } 複製程式碼
介面程式碼如下:
<script> export default { name: 'app', created() { console.log('打印出this.$store.state.count的結果',this.$store.state.count); }, } </script> 複製程式碼
執行結果: 成功打印出this.$store.state.count的值為0
二. vuex中的getter方法的實現
main.js程式碼如下:
let store = new Vuex.Store({ state: { count: 0 }, getters: { getStatePlusOne(state) { return state.count + 1 } } }, Vue); new Vue({ store, render: h => h(App), }).$mount('#app') 複製程式碼
store.js的程式碼如下:
export class Store { constructor(options = {}, Vue) { this.options = options; this.getters = {} Vue.mixin({ beforeCreate: vuexInit }); forEachValue(options.getters, (getterFn, getterName) => { registerGetter(this, getterName, getterFn); }) } get state() { return this.options.state; } } function registerGetter(store, getterName, getterFn) { Object.defineProperty(store.getters, getterName, { get: () => { return getterFn(store.state) } }) } // 將物件中的每一個值放入到傳入的函式中作為引數執行 function forEachValue(obj, fn) { Object.keys(obj).forEach(key => fn(obj[key], key)); } function vuexInit() { const options = this.$options if (options.store) { // 元件內部設定了store,則優先使用元件內部的store this.$store = typeof options.store === 'function' ? options.store() : options.store } else if (options.parent && options.parent.$store) { // 元件內部沒有設定store,則從根App.vue下繼承$store方法 this.$store = options.parent.$store } } 複製程式碼
介面程式碼如下:
<script> export default { name: 'app', created() { console.log('打印出this.$store.getters.getStatePlusOne的結果',this.$store.getters.getStatePlusOne); }, } </script> 複製程式碼
執行結果: 成功打印出this.$store.getters.getStatePlusOne的值為1
三. mutation和commit方法的實現
main.js程式碼如下:
let store = new Vuex.Store({ state: { count: 0 }, mutations: { incrementFive(state) { // console.log('初始state', JSON.stringify(state)); state.count = state.count + 5; } }, getters: { getStatePlusOne(state) { return state.count + 1 } } }, Vue); 複製程式碼
store.js的程式碼如下:
export class Store { constructor(options = {}, Vue) { Vue.mixin({ beforeCreate: vuexInit }) this.options = options; this.getters = {}; this.mutations = {}; const { commit } = this; this.commit = (type) => { return commit.call(this, type); } forEachValue(options.getters, (getterFn, getterName) => { registerGetter(this, getterName, getterFn); }); forEachValue(options.mutations, (mutationFn, mutationName) => { registerMutation(this, mutationName, mutationFn) }); this._vm = new Vue({ data: { state: options.state } }); } get state() { // return this.options.state; // 無法完成頁面中的雙向繫結,所以改用this._vm的形式 return this._vm._data.state; } commit(type) { this.mutations[type](); } } function registerMutation(store, mutationName, mutationFn) { store.mutations[mutationName] = () => { mutationFn.call(store, store.state); } } function registerGetter(store, getterName, getterFn) { Object.defineProperty(store.getters, getterName, { get: () => { return getterFn(store.state) } }) } // 將物件中的每一個值放入到傳入的函式中作為引數執行 function forEachValue(obj, fn) { Object.keys(obj).forEach(key => fn(obj[key], key)); } function vuexInit() { const options = this.$options if (options.store) { // 元件內部設定了store,則優先使用元件內部的store this.$store = typeof options.store === 'function' ? options.store() : options.store } else if (options.parent && options.parent.$store) { // 元件內部沒有設定store,則從根App.vue下繼承$store方法 this.$store = options.parent.$store } } 複製程式碼
介面程式碼如下:
<script> export default { name: 'app', created() { console.log('打印出this.$store.getters.getStatePlusOne的結果',this.$store.getters.getStatePlusOne); }, mounted() { setTimeout(() => { this.$store.commit('incrementFive'); console.log('store state自增5後的結果', this.$store.state.count); }, 2000); }, computed: { count() { return this.$store.state.count; } } } </script> 複製程式碼
執行結果:成功在2秒之後輸出count自增5後的結果5
四. actions和dispatch方法的實現
main.js程式碼如下:
let store = new Vuex.Store({ state: { count: 0 }, actions: { countPlusSix(context) { context.commit('plusSix'); } }, mutations: { incrementFive(state) { // console.log('初始state', JSON.stringify(state)); state.count = state.count + 5; }, plusSix(state) { state.count = state.count + 6; } }, getters: { getStatePlusOne(state) { return state.count + 1 } } }, Vue); 複製程式碼
store.js的程式碼如下:
export class Store { constructor(options = {}, Vue) { Vue.mixin({ beforeCreate: vuexInit }) this.options = options; this.getters = {}; this.mutations = {}; this.actions = {}; const { dispatch, commit } = this; this.commit = (type) => { return commit.call(this, type); } this.dispatch = (type) => { return dispatch.call(this, type); } forEachValue(options.actions, (actionFn, actionName) => { registerAction(this, actionName, actionFn); }); forEachValue(options.getters, (getterFn, getterName) => { registerGetter(this, getterName, getterFn); }); forEachValue(options.mutations, (mutationFn, mutationName) => { registerMutation(this, mutationName, mutationFn) }); this._vm = new Vue({ data: { state: options.state } }); } get state() { // return this.options.state; // 無法完成頁面中的雙向繫結,所以改用this._vm的形式 return this._vm._data.state; } commit(type) { this.mutations[type](); } dispatch(type) { return this.actions[type](); } } function registerMutation(store, mutationName, mutationFn) { store.mutations[mutationName] = () => { mutationFn.call(store, store.state); } } function registerAction(store, actionName, actionFn) { store.actions[actionName] = () => { actionFn.call(store, store) } } function registerGetter(store, getterName, getterFn) { Object.defineProperty(store.getters, getterName, { get: () => { return getterFn(store.state) } }) } // 將物件中的每一個值放入到傳入的函式中作為引數執行 function forEachValue(obj, fn) { Object.keys(obj).forEach(key => fn(obj[key], key)); } function vuexInit() { const options = this.$options if (options.store) { // 元件內部設定了store,則優先使用元件內部的store this.$store = typeof options.store === 'function' ? options.store() : options.store } else if (options.parent && options.parent.$store) { // 元件內部沒有設定store,則從根App.vue下繼承$store方法 this.$store = options.parent.$store } } 複製程式碼
介面程式碼如下:
export default { name: 'app', created() { console.log('打印出this.$store.getters.getStatePlusOne的結果',this.$store.getters.getStatePlusOne); }, mounted() { setTimeout(() => { this.$store.commit('incrementFive'); console.log('store state自增5後的結果', this.$store.state.count); }, 2000); setTimeout(() => { this.$store.dispatch('countPlusSix'); console.log('store dispatch自增6後的結果', this.$store.state.count); }, 3000); }, computed: { count() { return this.$store.state.count; } } } 複製程式碼
執行結果: 成功在3秒之後dipatch自增6輸出11
五. module方法的實現
main.js程式碼如下:
const pageA = { state: { count: 100 }, mutations: { incrementA(state) { state.count++; } }, actions: { incrementAAction(context) { context.commit('incrementA'); } } } let store = new Vuex.Store({ modules: { a: pageA }, state: { count: 0 }, actions: { countPlusSix(context) { context.commit('plusSix'); } }, mutations: { incrementFive(state) { // console.log('初始state', JSON.stringify(state)); state.count = state.count + 5; }, plusSix(state) { state.count = state.count + 6; } }, getters: { getStatePlusOne(state) { return state.count + 1 } } }, Vue); 複製程式碼
store.js的程式碼如下:
let _Vue; export class Store { constructor(options = {}, Vue) { _Vue = Vue Vue.mixin({ beforeCreate: vuexInit }) this.getters = {}; this._mutations = {}; // 在私有屬性前加_ this._wrappedGetters = {}; this._actions = {}; this._modules = new ModuleCollection(options) const { dispatch, commit } = this; this.commit = (type) => { return commit.call(this, type); } this.dispatch = (type) => { return dispatch.call(this, type); } const state = options.state; const path = []; // 初始路徑給根路徑為空 installModule(this, state, path, this._modules.root); this._vm = new Vue({ data: { state: state } }); } get state() { // return this.options.state; // 無法完成頁面中的雙向繫結,所以改用this._vm的形式 return this._vm._data.state; } commit(type) { this._mutations[type].forEach(handler => handler()); } dispatch(type) { return this._actions[type][0](); } } class ModuleCollection { constructor(rawRootModule) { this.register([], rawRootModule) } register(path, rawModule) { const newModule = { _children: {}, _rawModule: rawModule, state: rawModule.state } if (path.length === 0) { this.root = newModule; } else { const parent = path.slice(0, -1).reduce((module, key) => { return module._children(key); }, this.root); parent._children[path[path.length - 1]] = newModule; } if (rawModule.modules) { forEachValue(rawModule.modules, (rawChildModule, key) => { this.register(path.concat(key), rawChildModule); }) } } } function installModule(store, rootState, path, module) { if (path.length > 0) { const parentState = rootState; const moduleName = path[path.length - 1]; _Vue.set(parentState, moduleName, module.state) } const context = { dispatch: store.dispatch, commit: store.commit, } const local = Object.defineProperties(context, { getters: { get: () => store.getters }, state: { get: () => { let state = store.state; return path.length ? path.reduce((state, key) => state[key], state) : state } } }) if (module._rawModule.actions) { forEachValue(module._rawModule.actions, (actionFn, actionName) => { registerAction(store, actionName, actionFn, local); }); } if (module._rawModule.getters) { forEachValue(module._rawModule.getters, (getterFn, getterName) => { registerGetter(store, getterName, getterFn, local); }); } if (module._rawModule.mutations) { forEachValue(module._rawModule.mutations, (mutationFn, mutationName) => { registerMutation(store, mutationName, mutationFn, local) }); } forEachValue(module._children, (child, key) => { installModule(store, rootState, path.concat(key), child) }) } function registerMutation(store, mutationName, mutationFn, local) { const entry = store._mutations[mutationName] || (store._mutations[mutationName] = []); entry.push(() => { mutationFn.call(store, local.state); }); } function registerAction(store, actionName, actionFn, local) { const entry = store._actions[actionName] || (store._actions[actionName] = []) entry.push(() => { return actionFn.call(store, { commit: local.commit, state: local.state, }) }); } function registerGetter(store, getterName, getterFn, local) { Object.defineProperty(store.getters, getterName, { get: () => { return getterFn( local.state, local.getters, store.state ) } }) } // 將物件中的每一個值放入到傳入的函式中作為引數執行 function forEachValue(obj, fn) { Object.keys(obj).forEach(key => fn(obj[key], key)); } function vuexInit() { const options = this.$options if (options.store) { // 元件內部設定了store,則優先使用元件內部的store this.$store = typeof options.store === 'function' ? options.store() : options.store } else if (options.parent && options.parent.$store) { // 元件內部沒有設定store,則從根App.vue下繼承$store方法 this.$store = options.parent.$store } } 複製程式碼
主介面程式碼如下:
<template> <div id="app"> ==============主頁================<br> 主頁數量count為: {{count}}<br> pageA數量count為: {{countA}}<br> ==========以下為PageA內容==========<br> <page-a></page-a> </div> </template> <script> import pageA from './pageA'; export default { name: 'app', components: { pageA }, created() { console.log('打印出this.$store.getters.getStatePlusOne的結果',this.$store.getters.getStatePlusOne); }, mounted() { setTimeout(() => { this.$store.commit('incrementFive'); console.log('store state自增5後的結果', this.$store.state.count); }, 2000); setTimeout(() => { this.$store.dispatch('countPlusSix'); console.log('store dispatch自增6後的結果', this.$store.state.count); }, 3000); }, computed: { count() { return this.$store.state.count; }, countA() { return this.$store.state.a.count; } } } </script> 複製程式碼
pageA頁面如下:
<template> <div> 頁面A被載入 </div> </template> <script> export default { name: 'pageA', mounted() { setTimeout(() => { this.$store.dispatch('incrementAAction'); }, 5000) }, } </script> 複製程式碼
執行結果: 在5秒後A頁面觸發incrementAAction,主介面中的countA變化為101,成功
自此:基本用了150行左右的程式碼實現了vuex 80%左右的功能了,其中還有namespace等不能夠使用,其他基本都和原始碼語法相同,如果你有興趣仔細再看看,可以移步 github倉庫程式碼 ,程式碼是建立在閱讀了vuex原始碼之後寫的,所以看完了本文的程式碼,再去看vuex的程式碼,相信你一定會一目瞭然
六. 實現:Vue.use(Vuex)
最後為了和vuex原始碼做到最相似,同樣使用Vue.use(Vuex),使用如下的程式碼進行實現:
export function install(_Vue) { Vue = _Vue; Vue.mixin({ beforeCreate: function vuexInit() { const options = this.$options; if (options.store) { this.$store = options.store; } else if (options.parent && options.parent.$store) { this.$store = options.parent.$store; } } }) } 複製程式碼
部門正在招新,為騰訊企業產品部,隸屬CSIG事業群。福利不少,薪水很高,就等你來。有興趣請猛戳下方兩個連結。 www.lagou.com/jobs/521039… www.zhipin.com/job_detail/…
參考資料: