Vue2中的mapState和mapGetters和mapActions和mapMutations

在如下链接,说明了getters和基础的应用

Vue2中使用Vuex_Aricanv的博客-CSDN博客在App.js中,通过 $store.commit() 将方法回调名,以及数据,直接传给mutations对象,在mutations对象中写方法回调,将数据进行处理使用。由于已经引入Vuex,所以在this中会有$store方法, store方法中存在 commit,dispatch,getters,state等属性具体属性见下图。并且在其中进行逻辑运算,然后再通过 context.commit('大写方法名区别actions中的方法',value)方法名(context,value){https://blog.csdn.net/weixin_44685106/article/details/130450769?spm=1001.2014.3001.5501

这一节说明 使用mapState 和 mapGetters mapActions mapMutations 

 在App.vue中

<template>
  <div class="title">
    <h2>当前求和为: {{ sum }}</h2>
    <h2>当前通过复杂运算求和: {{ bigSum }}</h2>
	<br>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
	</select>
    <button @click="jia(n)">+</button>
    <button @click="jian(n)">-</button>
  </div>
</template>

<script>
import {mapState,mapGetters} from 'vuex'

export default {
  name: 'App',
  data() {
    return {
      n: 1 //用户选择数字
    }
  },
  computed:{
    //sum(){
	// 	return this.$store.state.sum
	// },
	...mapState(['sum'])
    // bigSum(){
	// 	return this.$store.getters.bigSum
	// },
	...mapGetters(['bigSum'])
  }
  },
  methods: {
    // jia() {
    //   this.$store.commit('JIA', this.n) // 简单逻辑 通过commit 直接将行为 递给 mutations对象
    // },
    // jian() {
    //   this.$store.commit('JIAN', this.n)
    // },

    //通过mapMutations中的方法,会调用commit去联系Mutations

    ...mapMutations({jia:'JIA',jian:'JIAN'}),
    // ji() {
    //   this.$store.dispatch('ji', this.n) // 复杂逻辑  先递交给 actions 通过它 递给mutations对象
    // },
    // slide() {
    //   this.$store.dispatch('slide', this.n)
    // }

    //通过mapMutations中的方法,会调用dispatch去联系Actions
    ...mapActions({ji:'ji',slide:'slide'})
  }
}
</script>

在对象中写法:...mapxxx可以展开对象中的每一项

完整写法在注释中,通过Vuex调用里面的方法进行代码重复调用

注意:用mapMutations和mapActions需要在模板中调用函数时传递参数

以上内容仅供学习使用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值