store定制软件开发是一个管理状态,在vuex中使用。
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({ state: { //定制软件开发这里放全局参数 }, mutations: { //这里是set方法 }, getters: { //这里是get方法,定制软件开发并且每次打开浏览器优先执行该方法,获取所有的状态 }, actions: { // 处理state的方法体 }, modules: {//这里是我自己理解的是为了给全局变量分组,所以需要写提前声明其他store文件,然后引入这里 }})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
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) },
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
接着调用了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, '') },
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
我们直接看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 } });}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
通过debug
我们可以看到这个方法已经被编译成了这个样子,但是第一个参数,拥有的属性,就是上面源码中的参数。
这个方法传过来的值
接着,调用下面三个方法
上面的意思相当于
this.$store.commit('setDemoValue', value);
- 1
就会调用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 },
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
调用完成后,执行getters更新状态
activeRow (state) { debugger let { layoutSections, activeSection } = state return layoutSections[activeSection] || [] }
- 1
- 2
- 3
- 4
- 5