Vuex rebuilt by vue [Part 2]

Article directory

  • Copyright Notice
  • Modularity of Vuex
  • Get state data in Vuex module
  • Get getters data in Vuex module
  • Get the mutations method in the Vuex module
  • Get the actions method in the module
  • Summarize

Copyright Statement

  • The content of this blog is based on my personal study notes from the Dark Horse Programmer course. I hereby declare that all copyrights belong to Dark Horse Programmers or related rights holders. The purpose of this blog is only for personal learning and communication, not commercial use.
  • I try my best to ensure accuracy when organizing my study notes, but I cannot guarantee the completeness and timeliness of the content. The content of this blog may become outdated over time or require updating.
  • If you are a Dark Horse programmer or a related rights holder, if there is any copyright infringement, please contact me in time and I will delete it immediately or make necessary modifications.
  • For other readers, please abide by relevant laws, regulations and ethical principles when reading the content of this blog, refer to it with caution, and bear the resulting risks and responsibilities at your own risk. Some of the views and opinions in this blog are my own and do not represent the position of Dark Horse Programmers.

Modularization of Vuex

  • Vuex is a state management library for Vue.js applications. A Vuex module is an independent part that encapsulates its own state, mutations, actions, and getters. Create a Vuex module by defining an object that contains the module’s state, changes, actions, and getters. This object can then be passed to the Vuex store’s modules option to register the module.

Here is a simple Vuex module example:

// module.js
const module = {<!-- -->
  state: {<!-- -->
    count: 0
  },
  mutations: {<!-- -->
    increment(state) {<!-- -->
      state.count++
    }
  },
  actions: {<!-- -->
    incrementAsync({<!-- --> commit }) {<!-- -->
      setTimeout(() => {<!-- -->
        commit('increment')
      }, 1000)
    }
  },
  getters: {<!-- -->
    doubleCount(state) {<!-- -->
      return state.count * 2
    }
  }
}

export default module
  • To use this module in the Vuex store, you can import it and add it to the modules option:
import Vue from 'vue'
import Vuex from 'vuex'
import module from './module'

Vue.use(Vuex)

const store = new Vuex.Store({<!-- -->
  modules: {<!-- -->
    module
  }
})

export default store

Get state data in the Vuex module

  • The state of the submodule will be hung in the root-level state, and the attribute name is the module.
  • Use data from modules
  1. Access $store.state.modulename.xxx directly through the module name
  2. Mapping via mapState:
    1. Default root-level mapping mapState([ xxx’ ])
    2. Mapping of submodules: mapState(module name’, [xxx’]) – the namespace needs to be enabled namespaced:true
  • modules/user.js
const state = {<!-- -->
  userInfo: {<!-- -->
    name: 'zs',
    age: 18
  },
  myMsg: 'My data'
}

const mutations = {<!-- -->
  updateMsg (state, msg) {<!-- -->
    state.myMsg = msg
  }
}

const actions = {<!-- -->}

const getters = {<!-- -->}

export default {<!-- -->
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
  • $store direct access
$store.state.user.userInfo.name
  • mapState helper function access
...mapState('user', ['userInfo']),
...mapState('setting', ['theme', 'desc']),

Get getters data in Vuex module

  • The mapGetters function maps getters from modules to local computed properties. It receives an array of strings and/or objects.
  • Each item in the string array is a getter name, each key in the object is a local computed property name, and the value is a getter name.

Use data from getters in the module:

  1. Directly access $store.getters['module name/xxx '] through the module name
  2. Mapping via mapGetters
    1. Default root-level mapping mapGetters([ 'xxx' ])
    2. Mapping of submodules mapGetters('module name', ['xxx']) – namespace needs to be enabled: namespaced:true

Here’s an example using mapGetters:

<template>
  <div>
    <p>count: {<!-- -->{<!-- -->doubleCount}}</p>
  </div>
</template>

<script>
import {<!-- --> mapGetters } from 'vuex'

export default {<!-- -->
  computed: {<!-- -->
    //Map the `doubleCount` getter from the store module named `module`
    ...mapGetters('module', ['doubleCount'])
  }
}
</script>

Get the mutations method in the Vuex module

  • Calling method:
  1. Call $store.commit('module name/xxx ', additional parameters) directly through the store
  2. Mapping via mapMutations
    1. Default root-level mapping mapMutations([ 'xxx' ])
    2. Mapping of submodules mapMutations('module name', ['xxx']) – namespace needs to be enabled: namespaced:true
<button @click="setUser({ name: 'xiaoli', age: 80 })">Update personal information</button>
<button @click="setTheme('skyblue')">Update theme</button>

methods:{<!-- -->
//Mapping of sub-modules
...mapMutations('setting', ['setTheme']),
...mapMutations('user', ['setUser']),
}

Get the actions method in the module

  • The mutations and actions in the default module will be mounted globally. You need to enable the namespace before they will be mounted to submodules.

  • The mapActions function is used to map actions from the module to local methods.

  • Each item in the string array is an action name, each key in the object is a local method name, and the value is an action name.

  • Requirement: Update information after one second

    • modules/user.js
    const actions = {<!-- -->
      setUserSecond (context, newUserInfo) {<!-- -->
        // Encapsulate the asynchronous method in action
        setTimeout(() => {<!-- -->
          //Call mutation context. By default, the actions and mutations of your own module are submitted.
          context.commit('setUser', newUserInfo)
        }, 1000)
      }
    }
    
    • Son1.vue is called directly through the store
    <button @click="updateUser2">Update information in one second</button>
    
    methods:{<!-- -->
        updateUser2 () {<!-- -->
          // Call action dispatch
          this.$store.dispatch('user/setUserSecond', {<!-- -->
            name: 'xiaohong',
            age: 28
          })
        },
    }
    
    • Son2.vue mapActions mapping
    <button @click="setUserSecond({ name: 'xiaoli', age: 80 })">Update information after one second</button>
    
    methods:{<!-- -->
      ...mapActions('user', ['setUserSecond'])
    }
    

Summary

Category Use mode directly Use with helper methods
state $store.state.Module name.Data item name …mapState(‘module name’, [‘data item’]) or…mapState(‘module name’, {new name: original name})
getters $store.getters[‘module name/property name’] …mapGetters(‘module name’, [‘property name’]) or…mapGetters(‘module name’, {new name: original name})
mutations $store.commit(‘module name/method name’, other parameters) …mapMutations(‘ module name’, [‘method name’]) or…mapMutations(‘module name’, {new name: original name})
actions $store.dispatch(‘module name/method name’, other parameters) …mapActions(‘module name’, [‘ Method name’]) or…mapActions(‘module name’, {new name: original name})
How to use it in components In the component, use the $store object to obtain data and methods In the component, use the spread operator to directly call properties and methods, such as {{ age }} or @click=”updateAge(2)”