核心提示:下面这篇是承接上一篇的内容的,如果没看过上一篇的内容,建议先翻一下上一篇的内容vuex入门。咋们这篇的功能和上一篇的一样,App.vue的内容没改,改的只是将store.js整个文件拆分成各个模块,下...
下面这篇是承接上一篇的内容的,如果没看过上一篇的内容,建议先翻一下上一篇的内容vuex入门。咋们这篇的功能和上一篇的一样,App.vue的内容没改,改的只是将store.js整个文件拆分成各个模块,下面是我拆分成各个js文件一览:

在这里,actions、getters和mutaions文件我就不解释了,下面解释的是index.js和types.js文件还有state状态去哪了。首先state它是去了mutaions那里方便管理。我们的这个index.js文件是个入口文件,也就相当于我们之前写的store.js文件,只不过里面的actions、getters、mutaions和state都在别的模块里需要导入进来。而这个types.js文件是配置一些方法名,方便actions.js和mutaions.js文件的使用。
首先我们在index.js里是这样子写的
// 配置入口
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import actions from './actions'
import mutations from './mutations'
export default new Vuex.Store({
actions,
modules: {
mutations
}
})
为什么这里没有getters?为什么这里Vuex.Store里面需要用到modules?接下来我慢慢讲。然后App.vue里面有两个方法,我们就在types.js里面这样写:
export const INCREMENT = 'increment' export const DECREMENT = 'decrement'在actions.js中,我们可以通过这样写来将commit提交出去:
import * as types from './types'
// 或者可以这样写:
// import {INCREMENT, DECREMENT} from './types'
// 这个表示只是引出INCREMENT出来,上面那个带星号的是把所有都引过来。
export default {
increment: ({commit}) => {
commit(types.INCREMENT)
},
decrement: ({commit, state}) => {
commit(types.DECREMENT)
// 这里想获取state里面的属性要用下面这个写法,因为state在mutaions模块里
console.log(state.mutations.count)
}
}
mutaions.js文件里,需要将通过如下方式来获取commit并进行操作。因为最后面导出的模块有三个,所以在index.js里需要用modules来裹着mutaions:
// 可以用这个方法来代替下面的导入所有
// import {INCREMENT, DECREMENT} from './types'
import * as types from './types'
import getters from './getters'
const state = {
count: 10
}
const mutations = {
[types.INCREMENT]: (state) => {
state.count++
},
[types.DECREMENT]: (state) => {
state.count--
}
}
export default {
mutations,
getters,
state
}
而我们的getters.js文件就是这样写:
export default {
count: (state) => {
return state.count
}
}
最后,若想把state提取出去,应该这样子写法,index.js代码:
// 配置入口
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import actions from './actions'
import * as getters from './getters'
import state from './state'
import mutations from './mutations'
export default new Vuex.Store({
actions,
getters,
state,
mutations
})
actions.js代码:
import * as types from './types'
// 或者可以这样写:
// import {INCREMENT, DECREMENT} from './types'
// 这个表示只是引出INCREMENT出来,上面那个带星号的是把所有都引过来。
export default {
increment: ({commit}) => {
commit(types.INCREMENT)
},
decrement: ({commit}) => {
commit(types.DECREMENT)
}
}
mutations.js代码:
// 可以用这个方法来代替下面的导入所有
// import {INCREMENT, DECREMENT} from './types'
import * as types from './types'
export default {
[types.INCREMENT] (state) {
state.count++
},
[types.DECREMENT] (state) {
state.count--
}
}
state.js代码:
const state = {
count: 10
}
export default state
getters代码:
export const count = state => state.counttypes.js代码:
export const INCREMENT = 'increment' export const DECREMENT = 'decrement'


