Vuex 提供了一些辅助函数,可以简化在组件中使用 store 的代码。下面是常用的几个辅助函数:

  1. 'mapState':将 store 中的 state 映射到组件的计算属性中。
import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState({
      count: state => state.count
    })
  }
}
  1. 'mapGetters':将 store 中的 getters 映射到组件的计算属性中。
import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters([
      'doneTodosCount'
    ])
  }
}
  1. 'mapMutations':将 store 中的 mutations 映射到组件的方法中。
import { mapMutations } from 'vuex'

export default {
  methods: {
    ...mapMutations([
      'increment', 
      'decrement'
    ])
  }
}
  1. 'mapActions':将 store 中的 actions 映射到组件的方法中。
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions([
      'incrementAsync',
      'decrementAsync'
    ])
  }
}

使用辅助函数可以使代码更加简洁,同时也方便了开发者的使用。

Vuex 辅助函数:简化组件中 Store 的使用

原文地址: http://www.cveoy.top/t/topic/lZDb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录