美文网首页Vue
vuex的辅助函数

vuex的辅助函数

作者: 开着五菱宏光的小白 | 来源:发表于2019-04-19 11:36 被阅读0次

辅助函数

解耦代码,可以让代码变得更简洁,只能在支持模块化的地方使用

  • mapState
  • mapGetters
  • mapMutations
  • mapActions

mapState

import { mapState } from 'vuex'

export default {
  computed: mapState(), // 这样写不能添加新的针对该组件的computed
  computed: {
    ...mapState(['state属性名', 'state属性名2']),
    ...mapState({
      自定义名字: 'state属性名',
      'state属性名': 'state属性名'
    }),
    // 相当于
    自定义名字 () {
      return this.$store.state.属性名
    }
  }
}

mapGetters

import { mapGetters } from 'vuex'

export default {
  computed: mapGetters(), // 这样写不能添加新的针对该组件的computed
  computed: {
    ...mapGetters(['getter名字']),
    ...mapGetters({
      自定义名字: 'getter名字'
    }),
    // 相当于
    自定义名字 () {
      return this.$store.getters.getter名字
    }
  }
}

mapMutations

mapMutation和mapActions放在methods中,会被映射成一个方法

import {mapMutations} from 'vuex'
export default {
  methods: {
    ...mapMutations(['mutation名字']),
    ...mapMutations({
      自定义名字: 'mutation名字'
    }),
    // 相当于
    自定义名字 (data) {
      this.$store.commit('mutation名字', data)
    },
    // 如果在提交前需要进行其他操作
    自定义名字 () {
      // 其他操作

      this.mutation名字()
    }
  }
}

mapActions

import {mapActions} from 'vuex'
export default {
  methods: {
    ...mapActions(['action名字']),
    ...mapActions({
      自定义名字: 'actions名字'
    }),
    // 相当于
    自定义名字 (data) {
      this.$store.dispatch('action名字', data)
    },
    // 如果需要有其他操作
    自定义名字 () {
      // 其他操作

      this.action名字()
    }
  }
}

如果不理解,就先不要去看,学会如果使用this.$store

相关文章

网友评论

    本文标题:vuex的辅助函数

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