简体   繁体   中英

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

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?

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']),
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM