关于前端:不超过20行实现一个小程序端使用的vuex

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的性能,能够依据本人的需要进行扩大和批改

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理