很多时候 , $store.state.count 、$store.dispatch('add') 这种写法又长又臭 , 很不方便 , 我们没使用 vuex 的时候 , 获取一个状态只需要 this.count , 执行一个方法只需要 this.add 就行了 , 使用 vuex 使写法变复杂了 ?

使用 mapState、mapGetters、mapActions 就不会这么复杂了。

以 mapState 为例 :

<template>
   <div>  
      <div>{{count}}</div>
      <input type="button" @click="$store.dispatch('addPlus')" value="+">
   </div>
</template>
<script>
import store from '../store/store'
import {mapState} from 'vuex';
export default {
  computed:
 //这里的三点叫做 : 扩展运算符
    ...mapState({
      count:state=>state.count
    })
//第二种方法
 //...mapState(['count'])
}
</script>

相当于 :

<template>
   <div>  
      <div>{{count}}</div>
      <input type="button" @click="$store.dispatch('addPlus')" value="+">
   </div>
</template>
<script>
import store from '../store/store'
import {mapState} from 'vuex';
export default {
   computed:{
    count(){
        return this.$store.state.count;
    }
  }
}
</script>

mapGetters、mapActions 和 mapState 类似 , mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods中。

Logo

前往低代码交流专区

更多推荐