[Getting started with Vue2+3 to practice] (20) Detailed explanation of VUE's Vuex state manager auxiliary function mapMutations module module state getters mutations actions method code implementation

Insert image description here

1. Auxiliary function - mapMutations

mapMutations is very similar to mapState. It extracts the methods located in mutations and we can import them.

import  {
    
     mapMutations } from 'vuex'
methods: {
    
    
    ...mapMutations(['addCount'])
}

The meaning of the above code is to import the mutations method into methods, which is equivalent to

methods: {
    
    
      // commit(方法名, 载荷参数)
      addCount () {
    
    
          this.$store.commit('addCount')
      }
 }

At this point, you can call it directly through this.addCount

<button @click="addCount">值+1</button>

But please note: mutations in Vuex require that asynchronous code cannot be written. If there are asynchronous ajax requests, they should be placed in actions.

2. Core concept - actions

State stores data, and mutations update data synchronously (convenient for monitoring data changes, updating views, etc., and for debugging tools to view changes).

actions are responsible for performing asynchronous operations

Note: mutations must be synchronized

Requirement: After one second, give a number to modify the state

Insert image description here

1. Define actions

mutations: {
    
    
  changeCount (state, newCount) {
    
    
    state.count = newCount
  }
}


actions: {
    
    
  setAsyncCount (context, num) {
    
    
    // 一秒后, 给一个数, 去修改 num
    setTimeout(() => {
    
    
      context.commit('changeCount', num)
    }, 1000)
  }
},

2. Called through dispatch in the component

setAsyncCount () {
    
    
  this.$store.dispatch('setAsyncCount', 666)
}

Insert image description here

3. Auxiliary function-mapActions

1. Goal: Master the auxiliary function mapActions and mapping methods

mapActions extracts the methods located in actions and maps them to component methods.

Sound2.view

import {
    
     mapActions } from 'vuex'
methods: {
    
    
   ...mapActions(['changeCountAction'])
}

//mapActions映射的代码 本质上是以下代码的写法
//methods: {
    
    
//  changeCountAction (n) {
    
    
//    this.$store.dispatch('changeCountAction', n)
//  },
//}

You can call it directly through this. method

<button @click="changeCountAction(200)">+异步</button>

4. Core concepts - getters

In addition to state, sometimes we also need to filter out some data that meets the conditions from the state . These data are dependent on the state. In this case, getters are used.

For example, list is defined in state, which is an array of 1-10.

state: {
    
    
    list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}

In the component, all data greater than 5 need to be displayed. Normally, the list needs to be further processed in the component, but getters can help us achieve it.

1. Define getters

  getters: {
    
    
    // getters函数的第一个参数是 state
    // 必须要有返回值
     filterList:  state =>  state.list.filter(item => item > 5)
  }

2. Use getters

2.1 Original method-$store
<div>{
   
   { $store.getters.filterList }}</div>
2.2 Auxiliary functions - mapGetters
computed: {
    
    
    ...mapGetters(['filterList'])
}
 <div>{
   
   { filterList }}</div>

5. Summary of use

Insert image description here

6. Core concept - module

1. Goal

Master the core concepts of module creation

2. Question

Due to the use of a single state tree , all the state of the application will be concentrated into a relatively large object . When an application becomes very complex, store objects have the potential to become quite bloated.

What this sentence means is that if you put all the state in state, when the project becomes larger and larger, Vuex will become more and more difficult to maintain.

From this, there is the modularity of Vuex

Insert image description here

3. Module definition - prepare state

Define two modules user and setting

Manage the user's information status in user userInfomodules/user.js

const state = {
  userInfo: {
    name: 'zs',
    age: 18
  }
}

const mutations = {}

const actions = {}

const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}

The theme color and description desc of the project application are managed in setting.modules/setting.js

const state = {
  theme: 'dark'
  desc: '描述真呀真不错'
}

const mutations = {}

const actions = {}

const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}

In store/index.jsthe modules configuration item in the file, register these two modules

import user from './modules/user'
import setting from './modules/setting'

const store = new Vuex.Store({
    
    
    modules:{
    
    
        user,
        setting
    }
})

Using the data in the module, you can access it directly through the module name $store.state.模块名.xxx=>$store.state.setting.desc

It can also be mapped through mapState

7. Get the state data in the module

1. Goal:

Master the access syntax of state in the module

Although it has been divided into modules, the status of the submodule will still be hung in the root-level state, and the attribute name is the module name.

Insert image description here

2. Use data in modules

  1. Access $store.state.modulename.xxx directly through the module name
  2. Mapping via mapState:
  3. Default root-level mapping mapState([ 'xxx' ])
  4. Mapping of submodules: mapState('module name', ['xxx']) - the namespace needs to be turned on namespaced:true

modules/user.js

const state = {
  userInfo: {
    name: 'zs',
    age: 18
  },
  myMsg: '我的数据'
}

const mutations = {
  updateMsg (state, msg) {
    state.myMsg = msg
  }
}

const actions = {}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

3. Code examples

$store direct access

$store.state.user.userInfo.name

mapState helper function access

...mapState('user', ['userInfo']),
...mapState('setting', ['theme', 'desc']),

8. Get getters data in the module

1. Goal:

Master the access terms of getters in modules

2. Grammar:

Use data from getters in the module:

  1. Access directly via module name $store.getters['模块名/xxx ']
  2. Mapping via mapGetters
    1. Default root level mappingmapGetters([ 'xxx' ])
    2. Mapping of submodules mapGetters('模块名', ['xxx'])- namespace needs to be enabled

3. Code demonstration

modules/user.js

const getters = {
    
    
  // 分模块后,state指代子模块的state
  UpperCaseName (state) {
    
    
    return state.userInfo.name.toUpperCase()
  }
}

Son1.vue directly accesses getters

<!-- 测试访问模块中的getters - 原生 -->
<div>{
   
   { $store.getters['user/UpperCaseName'] }}</div>

Son2.vue accessed through namespace

computed:{
    
    
  ...mapGetters('user', ['UpperCaseName'])
}

9. Get the mutations method in the module

1. Goal:

Master the calling syntax of mutations in modules

2. Note:

By default, mutations and actions in the module will be mounted globally, and the namespace needs to be enabled before they can be mounted to submodules.

3. 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. Submodule mapping mapMutations('module name', ['xxx']) - namespace needs to be enabled

4. Code implementation

modules/user.js

const mutations = {
    
    
  setUser (state, newUserInfo) {
    
    
    state.userInfo = newUserInfo
  }
}

modules/setting.js

const mutations = {
    
    
  setTheme (state, newTheme) {
    
    
    state.theme = newTheme
  }
}

Son1.vue

<button @click="updateUser">更新个人信息</button> 
<button @click="updateTheme">更新主题色</button>


export default {
  methods: {
    updateUser () {
      // $store.commit('模块名/mutation名', 额外传参)
      this.$store.commit('user/setUser', {
        name: 'xiaowang',
        age: 25
      })
    }, 
    updateTheme () {
      this.$store.commit('setting/setTheme', 'pink')
    }
  }
}

Sound2.view

<button @click="setUser({ name: 'xiaoli', age: 80 })">更新个人信息</button>
<button @click="setTheme('skyblue')">更新主题</button>

methods:{
// 分模块的映射
...mapMutations('setting', ['setTheme']),
...mapMutations('user', ['setUser']),
}

10. Get the actions method in the module

1. Goal:

Master the calling syntax of action in the module (same principle - just compare it directly with mutation)

2. Note:

By default, mutations and actions in the module will be mounted globally, and the namespace needs to be enabled before they can be mounted to submodules.

3. Call syntax:

  1. Call $store.dispatch('module name/xxx ', additional parameters) directly through the store
  2. Mapping via mapActions
    1. Default root-level mapping mapActions([ 'xxx' ])
    2. Submodule mapping mapActions('module name', ['xxx']) - namespace needs to be enabled

4. Code implementation

need:

Insert image description here

modules/user.js

const actions = {
    
    
  setUserSecond (context, newUserInfo) {
    
    
    // 将异步在action中进行封装
    setTimeout(() => {
    
    
      // 调用mutation   context上下文,默认提交的就是自己模块的action和mutation
      context.commit('setUser', newUserInfo)
    }, 1000)
  }
}

Son1.vue is called directly through the store

<button @click="updateUser2">一秒后更新信息</button>

methods:{
    updateUser2 () {
      // 调用action dispatch
      this.$store.dispatch('user/setUserSecond', {
        name: 'xiaohong',
        age: 28
      })
    },
}

Son2.vue mapActions mapping

<button @click="setUserSecond({ name: 'xiaoli', age: 80 })">一秒后更新信息</button>

methods:{
    
    
  ...mapActions('user', ['setUserSecond'])
}

11. Summary of the use of Vuex modularity

1. Use directly

  1. state --> $store.state.Module name.Data item name
  2. getters --> $store.getters[' module name /property name']
  3. mutations --> $store.commit(' module name /method name', other parameters)
  4. actions --> $store.dispatch(' module name /method name', other parameters)

2. Use with helper methods

1.import { mapXxxx, mapXxx } from ‘vuex’

computed、methods: {

​ // ...mapState, ...mapGetters are placed in computed;

​ // ...mapMutations, ...mapActions are placed in methods;

​ …mapXxxx( 'module name' , ['data item|method']),

​ …mapXxxx( 'module name' , {new name: original name}),

}

{ { age }}2. Use properties or methods directly in components@click="updateAge(2)"

Guess you like

Origin blog.csdn.net/shenchengyv/article/details/135351875