简单的实现vuex的功能
手写vuex
vuex是vue的一个状态管理插件,现在使用的场景非常多,今天,自己简单的实现一下vuex的几个小功能,如state,getter,commit,mutations,dispatch,actions
,暂时先实现这么多,有精力的话再补充module,map等
。
vuex在vue中的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| // store.js文件,也就是配置store的文件 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0 }, getter: { getterCount(state) { return state.count + 5; } }, mutations: { add(state, num) { state.count += num; } }, actions: { addAction(state, num) { setTimeout(()=> { state.commit('add', num); }, 2000); } } })
// vue的main.js文件中引入store import store from './store' new Vue({ router, store, render: h => h(App) }).$mount('#app')
// vue具体页面使用 <template> <div class="hello"> <h2>state->{{$store.state.count}}</h2> <h2>getter->{{$store.getter.getterCount}}</h2> <h2>computed->{{mill}}</h2> <button @click="onAdd">add</button> <button @click="onAddDispatch">addDispatch</button> </div> </template> <script> export default { data() { return { } }, computed: { mill() { return this.$store.state.count + 2; } }, methods: { onAdd() { this.$store.commit('add', 15); }, onAddDispatch() { this.$store.dispatch('addAction', 10); } } } </script>
|
vuex的实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| let Vue; class Store { constructor(options = {}) { this.options = options; this.vueState = new Vue({ data() { return { state: options.state } } }); // 处理getter操作 this.getter = {}; Object.keys(this.options.getter).forEach(item=> { Object.defineProperty(this.getter, item, { get: ()=> { return this.options.getter[item](this.options.state); } }); }); } // commit方法和mutations commit(type, val) { Object.keys(this.options.mutations).forEach(item=> { if(item === type) { this.options.mutations[item](this.options.state, val); } }) } // dispatch方法和actions dispatch(type, val) { Object.keys(this.options.actions).forEach(item=> { if(item === type) { this.options.actions[item](this, val); } }) } // 获取Store的state,来源于this.vueState,是Vue的一个实例,可以实现了store.state的数据绑定更新页面 get state () { return this.vueState.state; } } // 供Vue.use()调用 function install(_Vue) { Vue = _Vue; Vue.mixin({ beforeCreate: function () { const options = this.$options; if (options.store) { this.$store = options.store; } else if (options.parent && options.parent.$store) { this.$store = options.parent.$store; } } }) } export default { Store, install }
|