工程目录
主要关注store 文件夹下的文件
store/index.js
import Vue from 'vue'import Vuex from 'vuex'// import getters from './store/getters.js'// import actions from './store/actions.js'// import mutations from './store/mutations.js'import types from './types'// children moduleimport users from './modules/users.js'Vue.use(Vuex)const state = { count: 1}const mutations = { [types.INCREMENT]: (state, n) => { state.count = state.count + n }, [types.DECREMENT]: (state, n) => { state.count = state.count - n }}const actions = { increment: (context, n = 1) => { context.commit(types.INCREMENT, n) }, decrement: (context, commit, n = 1) => { context.commit(types.DECREMENT, n) }}export default new Vuex.Store({ state, mutations, actions, modules: { users }})
store/modules/users.js
import types from '../types'const state = { username: 'xiaojf'}const mutations = { [types.CHANGEUSERNAME]: (state, username) => { state.username = username }}const actions = { changeUsername (context, username = 'zhangsan') { context.commit(types.CHANGEUSERNAME, username) }}export default { state, mutations, actions}
/components/test.vue
{ {name}}{ { this.$store.state.count}}this is users module state { { this.$store.state.users.username}}
/components/test.vue
this is test2 { { this.$store.state.count}}