Vuex 中的map映射mapState,mapGetters,mapMutations,mapActions

405 阅读1分钟

前置知识:vuex的基本使用,store的概念

Vuex 中的map映射

  问题场景:在获取state中的数据时,我们这样书写

<h2>value in root: {{$store.state.count}}</h2>

  然而每次获取某些数据都需要前面的一大串 this.$store.state.xxx

使用计算属性可以将其简化,这样就可以直接使用 {{ count }} 来代替 {{ $store.state.count }} 了

computed: {
    count(){
      return this.$store.state.count
    }
}

但是,如果要获取很多state中的数据,都使用计算属性的话,会造成这样的情况

computed: {
    count(){
      return this.$store.state.count
    },
    count1(){
      return this.$store.state.count1
    },
    count2(){
      return this.$store.state.count2
    }
    xxx(){},
    ...
}

存在大量的冗余,可读性差

可以使用mapState来简化

mapState

 mapState能够建立state数据中的映射

使用方法

 1.从vuex中按需导入导入mapState

import {mapState} from 'vuex'

 2.在computed中创建映射

注意,创建的方式有两种

  (1) 对象写法,以key:value的方式定义映射,key为当前组件中 该数据要使用的名称,value字符串为state中数据的名称

  (2) 数组写法,以字符串数组的形式定义映射,要求当前组件中 数据使用名称 和 state中数据名称相同

注意,mapState返回的是一个对象,使用 ... 来将对象中的每一项解析到computed中

computed: {
    //对象写法
    ...mapState({num:'count'})
    //等价于
    num(){
      return this.$store.state.count
    },
​
    //数组写法
    ...mapState(['count'])
    //等价于
    count(){
      return this.$store.state.count
    },
}

mapGetters

 mapGetters能够建立getters数据的映射,使用方法与上方类似

//导入
import {mapGetters} from 'vuex'
//定义
 computed: {
    ...mapGetters(['countMult10'])
    //等价于
    countMult10(){
      return this.$store.getters.countMult10
    }
 }
//使用——在template中
<h3>value 10X: {{countMult10}}</h3>

mapMutations

 原先,我们在调用commit方法执行Mutations中方法的时候是这样写的

methods: {
    incre(){
      this.$store.commit("ADD",this.chooseNum)
    },
    decre(){
      this.$store.commit("SUB",this.chooseNum)
    },
}

 如同前面所讲的一样,也存在大量的冗余,如this.$store.commit

使用mapMutations可以优化

import { mapMutations } from 'vuex'
export default {
  method: {
    //对象写法
    ...mapMutations({incre:"ADD"})
    //等价于
    incre(){
      this.$store.commit('ADD')
    }
​
    //数组写法
    ...mapMutations(['incre'])
    //等价于
    incre(){
      this.$store.commit('incre')
    }
  }
}

 注意,数组写法会声明一个与字符串同名的函数,commit同名方法【如上方10-12行】

 注意,无论是数组还是对象写法,都是无法向映射的方法传参的,如果需要向Mutations中的方法传参,那么在使用时要记得传入参数

<button @click="decre(chooseNum)">减一</button>
<button @click="incre(chooseNum)">加一</button>

mapActions

 和上面的mapMutations用法类似,只是它映射的是actions中声明的函数,

methods: {
    //对象写法
    ...mapActions({
      increLater:"addWait"
    })
    //等价于
    increLater(){
      this.$action.addWait()
    }
​
    //数组写法
    ...mapActions(['addWait'])
    //等价于
    addWait(){
      this.$action.addWait()
    }
}

注意,也需要在使用时传递参数