本文介绍了Vuex 中的 b/n mapState、mapGetters、mapActions、mapMutations 的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 vue/vuex 几个月了,我看到了 mapStatemapGettersmapActionsmapMutations但不知道除了 mapState 之外他们做了什么.

这就是我如何使用 mapState

//mutations.js用户:{地址: {},姓名: '',年龄: ''}

在我的代码中,我有这样的东西:

import { mapState } from 'vuex'导出默认{数据: {},计算:{...地图状态({地址:状态=>状态.用户.地址})}}

然后我可以在任何地方使用地址,但我不知道其他人是做什么用的.

谁能举个简单的例子?谢谢

解决方案

这些映射器都不是强制性的.他们的目标只是使在组件中创建计算属性或方法变得容易.它们处于最佳状态(避免重复).

mapState 是一个帮助器,可简化创建反映给定状态值的计算属性.

同样:

  • mapGetters 是一个帮助程序,它简化了计算 属性的创建,该属性反映了给定 getter 返回的值.
  • mapActions 是一个帮助器,它简化了创建 方法 的过程,该方法等同于对操作调用 dispatch.
  • mapMutations 是一个帮助程序,它简化了创建 方法 的过程,该方法等同于对突变调用 commit.

由于代码有所帮助,下面的演示显示了使用所有这些映射器的示例,以及它们不使用映射器的等效项.他们的行为完全一样.映射器只是让您编写更少的代码(考虑到这将在您应用的许多组件中重复).

const store = new Vuex.Store({严格:真实,状态:{名称:约翰"},突变:{更改名称(状态,数据){状态.名称 = 数据}},动作:{fetchRandomName({ commit }) {让 randomId = Math.floor(Math.random() * 12) + 1 ;axios.get("https://reqres.in/api/users/" + randomId).then(response => {commit('changeName', response.data.data.first_name)})}},吸气剂:{获取名称:状态 =>州名,getTransformedName: (state) =>(上或下) =>{返回上或下?state.name.toUpperCase() : state.name.toLowerCase()}}});新的 Vue({店铺,el: '#app',数据:{新名称:'鲍勃'},计算:{...Vuex.mapState(['name']),nameNoMapper() { return this.$store.state.name },...Vuex.mapGetters(['getName', 'getTransformedName']),getNameNoMapper() { return this.$store.getters.getName },getTransformedNameNoMapper() { return this.$store.getters.getTransformedName }},方法: {...Vuex.mapActions(['fetchRandomName']),...Vuex.mapMutations(['changeName']),fetchRandomNameNoMapper() { this.$store.dispatch('fetchRandomName') },changeNameNoMapper(newName) { this.$store.commit('changeName', newName) },}})
table, tr, td {字体系列:等宽;边框:1px纯黑色;边框折叠:折叠;}
<script src="https://unpkg.com/vue"></script><script src="https://unpkg.com/vuex"></script><script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script><div id="应用程序"><表格><tr><td style="width: 250px">使用映射器</td><td style="width: 310px">没有映射器</td></tr><tr><td>姓名:{{姓名}}
getName: {{ getName }}<br>getTransformedName(true): {{ getTransformedName(true) }}<br>getTransformedName(false): {{ getTransformedName(false) }}</td><td>nameNoMapper: {{ nameNoMapper }}
getNameNoMapper: {{ getNameNoMapper }}<br>getTransformedNameNoMapper(true): {{ getTransformedNameNoMapper(true) }}<br>getTransformedNameNoMapper(false): {{ getTransformedNameNoMapper(false) }}</td></tr><小时><button @click="fetchRandomName">操作:fetchRandomName</button>- <button @click="fetchRandomNameNoMapper">操作:fetchRandomNameNoMapper</button><br><小时><input v-model="newName"><button @click="changeName(newName)">MUTATION:changeName</button><button @click="changeNameNoMapper(newName)">MUTATION:changeNameNoMapper<;/按钮>

I have been using vue/vuex for months and I see mapState, mapGetters, mapActions, mapMutations but don't know what they do except for mapState.

This is how I use mapState

// mutations.js 
user: {
   address: {},
   name: '',
   age: ''
}

and in my code I have something like this:

import { mapState } from 'vuex'
export default {
  data: {},

  computed: {
   ...mapState({
    address: state => state.user.address
   })
  }
} 

then I can use address anywhere, but I don't know what the others are used for.

can someone give a simple example? thanks

解决方案

None of those mappers are mandatory. Their goal is just to make easy to create computed properties or methods in the components. They are DRY (avoid duplication) at its best.

mapState is a helper that simplifies creating a computed property that reflects the value of a given state.

Similarly:

  • mapGetters is a helper that simplifies creating a computed property that reflects the value returned by a given getter.
  • mapActions is a helper that simplifies creating a method that would be equivalent as calling dispatch on an action.
  • mapMutations is a helper that simplifies creating a method that would be equivalent as calling commit on an mutation.

Since code helps, the demo below shows examples of using all those mappers, and their equivalent without mappers. Their behavior is exactly the same. The mappers just allow you to write with less code (consider that this will be repeated in many, many components of your app).

const store = new Vuex.Store({
  strict: true,
  state: {name: "John"},
  mutations: {
  	changeName(state, data) {
    	state.name = data
    }
  },
  actions: {
    fetchRandomName({ commit }) {
      let randomId = Math.floor(Math.random() * 12) + 1  ;
      axios.get("https://reqres.in/api/users/" + randomId).then(response => {
        commit('changeName', response.data.data.first_name)
      })
    }
  },
  getters: {
    getName: state => state.name,
    getTransformedName: (state) => (upperOrLower) => {
      return upperOrLower ? state.name.toUpperCase() : state.name.toLowerCase()
    }
  }
});
new Vue({
  store,
  el: '#app',
  data: { newName: 'Bob' },
  computed: {
    ...Vuex.mapState(['name']),
    nameNoMapper() { return this.$store.state.name },
    ...Vuex.mapGetters(['getName', 'getTransformedName']),
    getNameNoMapper() { return this.$store.getters.getName },
    getTransformedNameNoMapper() { return this.$store.getters.getTransformedName }
  },
  methods: {
    ...Vuex.mapActions(['fetchRandomName']),
    ...Vuex.mapMutations(['changeName']),
    fetchRandomNameNoMapper() { this.$store.dispatch('fetchRandomName') },
    changeNameNoMapper(newName) { this.$store.commit('changeName', newName) },
  }
})
table, tr, td {
  font-family: monospace;
  border: 1px solid black;
  border-collapse: collapse;
}
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>

<div id="app">
  <table>
    <tr>
      <td style="width: 250px">With Mappers</td>
      <td style="width: 310px">Without Mappers</td>
    </tr>
    <tr>
      <td>
        name: {{ name }}<br>
        getName: {{ getName }}<br>
        getTransformedName(true): {{ getTransformedName(true) }}<br>
        getTransformedName(false): {{ getTransformedName(false) }}
      </td>
      <td>
        nameNoMapper: {{ nameNoMapper }}<br>
        getNameNoMapper: {{ getNameNoMapper }}<br>
        getTransformedNameNoMapper(true): {{ getTransformedNameNoMapper(true) }}<br>
        getTransformedNameNoMapper(false): {{ getTransformedNameNoMapper(false) }}
      </td>
    </tr>
  </table>
  <hr>
  <button @click="fetchRandomName">ACTION: fetchRandomName</button> - <button @click="fetchRandomNameNoMapper">ACTION: fetchRandomNameNoMapper</button><br>
  <hr>
  <input v-model="newName"><button @click="changeName(newName)">MUTATION: changeName</button><button @click="changeNameNoMapper(newName)">MUTATION: changeNameNoMapper</button>
</div>

这篇关于Vuex 中的 b/n mapState、mapGetters、mapActions、mapMutations 的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 21:42