vuex的主要作用是做数据管理,数据单向流,在vue的项目中基本上都会用到,对于初学者会感到很迷糊,觉的很神秘,其实它的原理相对还是比较简单的,下面是模仿vuex的原理自己实现一个简单的vuex
let Vue;
class Store {
constructor(options) {
// 把状态交给vue来管理
this.state = new Vue({
data: options.state,
});
this.mutations = options.mutations;
this.actions = options.actions;
options.getters && this.handleGetters(options.getters);
}
commit = (type, arg) => {
this.mutations[type](this.state, arg);
};
dispatch(type, arg) {
this.actions[type]({ commit: this.commit, state: this.state }, arg);
}
handleGetters(getters) {
this.getters = {};
Object.keys(getters).forEach((key) => {
Object.defineProperty(this.getters, key, {
get: () => {
return getters[key](this.state);
},
});
});
}
}
function install(_Vue) {
Vue = _Vue;
Vue.mixin({
beforeCreate() {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store;
}
},
});
}
export default { Store, install };
其实原理相对还是比较简单的,使用的话,还是和原本的vuex类似
// main.js
import Vuex from './kStore.js';
Vue.use(Vuex);
// 注册vuex模块
const store = new Vuex.Store({
state: {
count: 1,
},
mutations: {
add(state, n = 1) {
state.count += n;
},
},
});
new Vue({
store,
router,
render: (h) => h(App),
}).$mount('#app');
网友评论