When writing large front-end applications, managing state can be a daunting and tedious task.
For Vue.js, a Vuex plugin was developed for state management. By default, it has the following folder structure:
Folder structure in Vuex store
This folder structure could be used in small applications, but in large ones the source code is likely to look unreadable and ugly, and over time it becomes difficult to work with.
,
, . :
Vuex (. .: , , store/modules/user/mutations.js, .. )
, . , index.js, Vuex. , index.js , :
import Vue from "vue";
import Vuex from "vuex";
import state from './state.js'
import actions from './actions.js'
import mutations from './mutations.js'
import getters from './getters.js'
import user from './modules/user/index.js'
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
actions,
getters,
modules: {
user
}
});
«user», index.js, Vuex. , «user» , .
«user» state, actions, getters mutations modules/user/index.js :
import state from './state.js'
import mutations from './mutations.js'
import actions from './actions.js'
import getters from './getters.js'
export default {
namespaced: true,
state,
mutations,
getters,
actions,
}
, namespaced true. , , , . ...
- Vuex , Vuex, . , userAvatar «user» userAvatar (. .: mapState: ...mapState(['userAvatar'])}
). mapState (. .: ) :
import {mapState} from 'vuex'
export default {
computed: {
...mapState({
userAvatar: state => state.user.userAvatar
})
},
}
, :
export default {
userAvatar: "img-location"
};
, «user» . , , :
import {mapActions} from 'vuex'
export default {
methods: {
...mapActions("user", ["getUserInfo"]),
userInfo() {
this.getUserInfo()
// – (. .: , <..mapActions("user", ["getUserInfo"]),>), ,
//
this.$store.dispatch('user/getUserInfo')
// – getUserInfo
}
},
}
Vuex :
export default {
getUserInfo() {
alert('Successful')
}
}
. .
export default {
methods: {
setuserInfo() {
let data = {
name: 'Henry'
}
this.$store.commit('user/setUserInfo', data)
}
},
}
Vuex :
export default {
setUserInfo: (state, data) => {
state.user = data
}
}
. . – , :
export default {
getActiveUsers: state => {
return state.users.filter(x => x.active === true)
}
}
Above is the recommended way to declare or write a getter, but it can be accessed by mapping getters to fields of a computed property object, like this:
import {mapState} from 'vuex'
export default {
computed: {
...mapGetters('user', ['getActiveUsers'])
},
}
It's been a long journey, hopefully you've managed to use modular Vuex and write cleaner code.