美文网首页
vuex--mapState,mapActions,mapGet

vuex--mapState,mapActions,mapGet

作者: 变量只提升声明不提升赋值 | 来源:发表于2020-11-18 16:49 被阅读0次

vuex提供了四个api供外部访问store中的东西,
mapState,mapActions,mapGetters,mapMutations

具体用法如下

<script>
  import {mapState,mapActions,mapGetters,mapMutations} from 'vuex'
  export default {
    data(){
      return {

      }
    },
    mounted () {
      console.log(this.$store)
    },

    computed: {
      ...mapGetters(['evenOrOdd']),  //mapGetters方法返回的是一个对象这种写法就相当于是 getters[evenOrOdd]
        ...mapState(['count'])


      // evenOrOdd () {
      //   this.$store.getters.evenOrOdd  //调用store里的计算属性,不需要带括号,因为这里是去读取这个计算属性的值
      // }
    },
    methods:{
      ...mapActions(['increment','decrement','incrementIfOdd','incrementAsync'])
    }

    // methods: {
    //   increment () {
    //     this.$store.dispatch('increment')  //通过dispatch去分发通知,
    //   },
    //   decrement () {
    //     this.$store.dispatch('decrement')
    //   },
    //   incrementIfOdd () {
    //     this.$store.dispatch('incrementIfOdd')
    //   },
    //   incrementAsync () {
    //     this.$store.dispatch('incrementAsync')
    //   }
    // }
  }
</script>

首先引入这几个api,然后如果是state和getters中的属性,我们可以在计算属性中去使用mapGetters和mapState两个api去得到,

...mapGetters(['evenOrOdd'])首先,这个api的返回值是一个对象,我们传['evenOrOdd']这个值过去,其实的就相当于是在写 getters[evenOrOdd] 其实就是按照对象的属性名来获得属性值 而前面三个点是es6的新语法,用来获取每一项数据,并作参数排列,

 methods:{
      ...mapActions(['increment','decrement','incrementIfOdd','incrementAsync'])
    }
上面这一行代码翻译一下其实就是下面的代码
    // methods: {
    //   increment () {
    //     this.$store.dispatch('increment')  //通过dispatch去分发通知,
    //   },
    //   decrement () {
    //     this.$store.dispatch('decrement')
    //   },
    //   incrementIfOdd () {
    //     this.$store.dispatch('incrementIfOdd')
    //   },
    //   incrementAsync () {
    //     this.$store.dispatch('incrementAsync')
    //   }
    // }

几个api的用法是一样的,目的在于减少代码量,使代码看上去更简洁

ps:取值规则


719c7ab399c2ac6b68db7c28c459cad.png
map函数里传参总共分为单独传一个数组和传一个字符串加一个数组两种。
即mapxxx('xxx',['xxx','xxx'])和mapxxx(['xxx','xxx'])
第一种方式一般用于映射模块下的内容,第一个字符串为模块名 ,第二个数组里放的则是需要引入的函数名或变量名

第二种方式就是直接映射主模块下的东西了,直接通过名字引入。当然第二种方式也可以引入子模块的东西,但是需要在名称前面加上模块名字,如上图所示

相关文章

网友评论

      本文标题:vuex--mapState,mapActions,mapGet

      本文链接:https://www.haomeiwen.com/subject/ebbciktx.html