Vuex 中的mapActions怎么传递自定义参数?

1. 问题mapActions如何传递自定义参数

<template>
  <div class="footer">
    <p><button @click="reduce(num2)">3.子组件的按钮(vuex)</button></p>
  </div>
</template>

2. 结论

这里的mapActions会自动把reduce(20) 映射成this.$store.dispatch('decrement', 20)

<script>
  import {mapActions} from 'vuex'
  export default {
    data () {
      return {
        num2: 20
      }
    },
    methods: {
   	  // 这里如果要传入参数,无需额外处理,调用的时候直接传参数就行,他会自动映射
      ...mapActions({
        reduce: 'decrement'
      })
    }
  }
</script>

3. 完整代码

(Footer组件)

<template>
  <div class="footer">
    <p><button @click="reduce(num2)">3.子组件的按钮(vuex)</button></p>
  </div>
</template>

<script>
  import {mapActions} from 'vuex'
  export default {
    props: {
      footerMsg: String
    },
    data () {
      return {
        num: 20,
        num2: 20
      }
    },
    // 写法1:
    // methods: {
    //   reduce (param) {
    //     this.$store.dispatch('decrement', param)
    //   }
    // }

    // 写法2:
    // methods: mapActions({
    //   reduce: 'decrement'
    // })

    // 写法3:
    methods: {
      ...mapActions({
        reduce: 'decrement'
      })
    }
  }
</script>

<style scoped lang="less">
  .footer {
    h2 {
      font-size: 22px;
      color: green;
      font-weight: 700;
      margin-bottom: 20px;
    }
    p {
      font-size: 20px;
      color: green;
      font-weight: 700
    }
  }
</style>

(store.js文件)

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    num: 0
  },
  actions: {
    decrement ({commit}, param) {
      commit ('decrement', param)
    }
  },
  mutations: {
    decrement (state ,param) {
      this.state.num-=param
    }
  },
  modules: {
  }
})

4. 思考

  1. vuex 中数据是单向流动的,state =》components =》 actions =》mutations =》state ,如果需要传入参数,需要在组件和用户交互的时候传递,在某个组件的某个事件中(例如:点击事件)
  2. 参数的流向是一层一层向下的,从 components =》actions =》 mutations =》 state =》components,和数据的流向一致在这里插入图片描述
发布了32 篇原创文章 · 获赞 0 · 访问量 997

猜你喜欢

转载自blog.csdn.net/weixin_42588966/article/details/103346894