1、Vuex.js
let Vue;
const forEach = (obj, callbackk) => {
Object.keys(obj).forEach((key) => {
callbackk(key, obj[key]);
})
}
class Store {
constructor(options) {
this.options = options;
this.vm = new Vue({
data: {
state: options.state
}
});
this.state = this.vm.state;
const getters = options.getters;
this.getters = {};
forEach(getters, (key, value) => {
Object.defineProperty(this.getters, key, {
get: () => {
return value(this.state);
}
})
})
const mutations = options.mutations;
this.mutations = {};
forEach(mutations, (key, value) => {
this.mutations[key] = (payload) => {
value(this.state, payload);
}
})
const actions = options.actions;
this.actions = {};
forEach(actions, (key, value) => {
this.actions[key] = (payload) => {
value(this, payload);
}
})
}
commit(mutationName, payload) {
this.mutations[mutationName](payload);
}
dispatch(actionName, payload) {
this.actions[actionName](payload);
}
}
const install = (_Vue) => {
Vue = _Vue;
Vue.mixin({
beforeCreate() {
const store = this.$options.store;
this.$store = store ? store : (this.$parent && this.$parent.$store);
}
})
}
export default {
Store,
install
}
2、store.js
import Vue from 'vue';
import Vuex from './Vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
age: 10,
num: 20
},
getters: {
price(state) {
return state.age * 50;
}
},
mutations: {
changeAge(state, payload) {
state.age = payload;
}
},
actions: {
asyncChangeAge(store, payload) {
setTimeout(() => {
store.commit('changeAge', payload);
}, 1000);
}
}
});
export default store;