store是一个管理状态,在vuex中使用。

    1. import Vue from 'vue'
    2. import Vuex from 'vuex'
    3. Vue.use(Vuex)
    4. export default new Vuex.Store({
    5. state: {
    6. //这里放全局参数
    7. },
    8. mutations: {
    9. //这里是set方法
    10. },
    11. getters: { //这里是get方法,并且每次打开浏览器优先执行该方法,获取所有的状态 },
    12. actions: {
    13. // 处理state的方法体
    14. },
    15. modules: {
    16. //这里是我自己理解的是为了给全局变量分组,所以需要写提前声明其他store文件,然后引入这里
    17. }
    18. })

    store的执行顺序:
    打开浏览器 → getters → 组件调用actions中的方法 → mutations(设置state的值) → getters(更新数据)
    接着我直接从一个国外的项目,部分代码拷贝出来,进行详细解读。
    首先这是一个组件,有个点击click事件。

        onAddRow (data) {
          const initVal = data.map((val, idx) => {
            return {
              colGrid: { span: val },
              isCustom: 'btn-addCol'
            }
          })
          this.addRow(initVal)
        },
    

    接着调用了actions里的方法,该方法的写法就很6,那个{}里的东西是由Vuex提供的,只是将Store里的数据提了出来

      addRow ({ commit, state }, reload) {
        let { layoutSections } = state
        let _idx = layoutSections.length
        let _newLaypout = [...layoutSections, reload]
        // 调用set方法,set全局的state
        commit(types.UPDATE_LAYOUT_SECTIONS, _newLaypout)
        commit(types.UPDATE_ACTIVE_SECTION, _idx)
        commit(types.UPDATE_ACTIVE_PROP, '')
      },
    

    我们直接看Store源码,就会发现:

    function registerAction (store, type, handler, local) {
      const entry = store._actions[type] || (store._actions[type] = []);
      entry.push(function wrappedActionHandler (payload, cb) {
        // 这里就是主要的参数,我们如果想要使用,就可以在{}里声明它
        let res = handler.call(store, {
          dispatch: local.dispatch,
          commit: local.commit,
          getters: local.getters,
          state: local.state,
          rootGetters: store.getters,
          rootState: store.state
        }, payload, cb);
        if (!isPromise(res)) {
          res = Promise.resolve(res);
        }
        if (store._devtoolHook) {
          return res.catch(err => {
            store._devtoolHook.emit('vuex:error', err);
            throw err
          })
        } else {
          return res
        }
      });
    }
    

    通过debug
    image.png
    我们可以看到这个方法已经被编译成了这个样子,但是第一个参数,拥有的属性,就是上面源码中的参数。
    image.png
    这个方法传过来的值
    image.png
    接着,调用下面三个方法
    image.png
    上面的意思相当于

    this.$store.commit('setDemoValue', value);
    

    就会调用mutations的set方法

      [types.UPDATE_LAYOUT_SECTIONS] (state, load) {
        state.layoutSections = load
      },
      [types.UPDATE_ACTIVE_SECTION] (state, load) {
        state.activeSection = load
      },
      [types.UPDATE_ACTIVE_PROP] (state, load) {
        state.activeProp = load
      },
    

    调用完成后,执行getters更新状态

      activeRow (state) {
        debugger
        let { layoutSections, activeSection } = state
        return layoutSections[activeSection] || []
      }