调用Mutation函数的方式

调用Mutation函数的方式

第一种:this.$store.commit()

// 触发mutation
methods: {
    handle1() {
        //触发mutations的第一种方式
        this.$store.commit ( 'add ' )
    }
}

可以在触发mutations 时传递参数:

//定义Mutation
const store = new vuex.store({
    state: {
	count: 0,
    },
    mutations: {
        addN (state, step){
            //变更状态
        	state.count += step
        }
	}
})

第二种:将指定的 mutations函数,映射为当前组件的methods函数

this.$store.commit()是触发mutations的第一种方式,触发mutations的第二种方式:

// 1.从vuex中按需导入mapMutations函数
import ( mapMutations ] from 'vuex'

通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法:

// 2.将指定的 mutations函数,映射为当前组件的methods函数
methods : {
...mapMutations ( [ 'sub', 'subN' ])

}

减法计算器应用实例

减法计算器示例:

<template>
  <div>
    <!-- 访问共享数据count {{ count }} -->
    <h3>当前最新的count值为:{{ count }}</h3>
    <button @click="btnhandler1">-1</button>
    <button @click="btnhandler2">-N</button>
  </div>
</template>

<script>
// 1.从 vuex中按需导入mapstate函数
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {}
  },
  //   2.将全局数据,映射为当前组件的计算属性
  computed: {
    ...mapState(['count']),
  },
  methods: {
    //  把store中的sub函数 映射为当前组件的mutations
    ...mapMutations(['sub', 'subN']),
    btnhandler1() {
      this.sub()
    },
    btnhandler2() {
      this.subN(3)
    },
  },
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值