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的功能,可以根据自己的需求进行扩展和修改
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net