What is the exact purpose of using mapActions in vue js?

Viewed 5085

As I am learning Vue js, I use mapState in many parts of my code for updating changes in rendering, whenever a change occurs in store layer. Recently, I also came to know about mapActions in vuex. But in most of the examples I search, I only use to see mapState. So, what is mapAction and it's exact purpose?

2 Answers

In Vuex, actions are (usually) asynchronous operations which carry out mutations, as opposed to direct updates to the state. mapActions is just a helper that lets you call those methods from within a Vue component. You can find more info here: https://vuex.vuejs.org/guide/actions.html

In the component, you can dispatch actions through this.$store.dispatch, or use mapActions to bind actions to the component's methods.

Usually, actions may belong to a namespace, and mapActions can work well in this case.

// use $store.dispatch
methods: {
  addTodo() {
    this.$store.dispatch('xxx/yyy/zzz/addTodo');
  },
  removeTodo() {
    this.$store.dispatch('xxx/yyy/zzz/removeTodo');
  },
},
// use mapActions
methods: {
  ...mapActions('xxx/yyy/zzz', ['addTodo', 'removeTodo']),
},
Related