const createStore = (options) => {let state = options.state || {};
const mutations = options.mutations || {};
const actions = options.actions || {};
const commit = (type, payload) => {const mutation = mutations[type];
mutation(state, payload);
};
const dispatch = (type, payload) => {const action = actions[type];
action({commit, state}, payload);
};
const getState = () => {return state;};
return {
commit,
dispatch,
getState
};
};
module.exports = createStore;
创立:
// index.js
const createStore = require('path/to/store.js');
const store = createStore({
state: {count: 0},
mutations: {increment(state, payload) {state.count += payload;}
},
actions: {asyncIncrement({ commit}, payload) {setTimeout(() => {commit('increment', payload);
}, 1000);
}
}
});
module.exports = store;
在利用的其余中央,能够通过 store.dispatch 和 store.commit 办法来散发 action 和 mutation,例如:
// page.js
const store = require('path/to/index.js');
Page({onLoad: function () {store.dispatch('asyncIncrement', 1);
},
onUnload: function () {const state = store.getState();
console.log(state.count);
}
});
这个简略的状态治理库只实现了最根本的状态、mutation 和 action 的性能,能够依据本人的需要进行扩大和批改