Vuex is a state management mode specially developed for vuue.js applications. It is easy to centrally manage the state of all components of the entire application and has a set of responsive rules to ensure that state changes are predictable

Vuex status management process

The State of State is bound to the component. When the user interacts in the component and there is a State change, Actions are distributed through Dispatch. Instead of directly submitting State change, asynchronous request can be made through Actions, and then Commit to Mutation for State change. The state is well controlled by Mutation.

Vuex core concepts

Store An application has only one Store. It is a container that contains all application states and cannot be modified directly

State is stored in Store, maintains State, and is responsive

Getter computes properties and can perform complex computations for caching

Mutation State modification must be performed by Mutation

Action Can operate asynchronously

Too many Moudule states are difficult to manage. You can use modules to split the state into multiple modules

Using Vuex

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: {}
})

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')
Copy the code

Access to the State

Import {mapState} from 'vuex' export default {computed: {// Equivalent to count: state => state.count // alias... mapState([ num: 'count', message: 'msg']) ... mapState(['count', 'msg']) }Copy the code

The use of Getter

new Vuex.Store({ getters: { reversMsg (state) { return state.msg.split('').reserse().join('') } }) import { mapGetters } from 'vuex' export default { computed: { ... mapGetters(['reversMsg']) }Copy the code

The use of Mutation

new Vuex.Store({
  mutations: {
    increate (state, payload) {
      state.count += payload
    }
})


import { mapMutations } from 'vuex'
export default {
  methods: {
    ...mapGetters(['increate'])}
Copy the code

The use of the Action

new Vuex.Store({ actions: { increateAsync (context, payload) { setTimeOut(() => { context.commit('increate', payload) }, 2000) } }) import { mapAtions } from 'vuex' export default { methods: { ... mapGetters(['increateAsync'])Copy the code

The use of the Module

Mutations, actions new vuex. Store({modules: {// import module products, cart}}) // enable namespace // add namespaced to each module export: true export default {namespaced: Import {mapMutations} from 'vuex' export default {methods: { mapGetters('products', ['increate']) } }Copy the code