Vuex的简单实例(4)

vuex之mutation

1)你可以在组件中使用 this.$store.commit(‘xxx’) 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用。看之前文章中的代码:

// 修改密码状态 store.js
mutations: {
	changePassword(state, data) {
	    state.password = data
	}
}

// Login.vue
methods: {
    loginHandle() {
      // 修改password状态
      this.$store.commit("changePassword", this.password); 
    }
  }

vuex之mutation提交载荷(传参)

1)可以向store.commit传入额外的参数,即mutation的载荷。在mutations里面添加2个操作count的方法,一个用来增加,一个用来重置

mutations: {
  // ...
  addCount(state, n) {
    state.count += n
  },
  resetCount(state, data) {
    state.count = data;
  }
}

2)在Home.vue的mapState中加入count

// template
<p>{{ count }}</p>
<Button @click="add">+</Button>
<Button @click="reset">reset</Button>

// computed
...mapState(['isLogin', 'username', 'password', 'count']),

3)调用mutations里面添加的操作count的方法

methods: {
  add () {
    this.$store.commit('addCount', 1)
  },
  reset () {
    this.$store.commit('resetCount', 0)
  }
}

在这里插入图片描述
4)提交载荷传参

// 使用对象形式的载荷也能实现这种效果
// 很多时候,尤其是当数据比较复杂,使用对象形式的载荷会更好。修改addCount与resetCount
addCount(state, payload) {
    state.count += payload.n
},
resetCount(state, payload) {
    state.count = payload.data;
}

// 调用的时候以对象的形式传参
methods: {
	add() {
	  this.$store.commit({
	    type: "addCount",
	    n: 1
	  });
	},
	reset() {
	  this.$store.commit({
	    type: "resetCount",
	    data: 0
	  });
	}
}

Vuex之mapMutations

1)与前面mapState、mapGetters性质相似的辅助函数,在Home.vue中把store.js中的addCount、resetCount方法加入

...mapMutations(["addCount", "resetCount"])

// 调用的时候
add() {
  this.addCount({ n: 1 });
},
reset() {
  this.resetCount({ data: 0 });
}
// 更多形式
// memthod2
// add() {
//   this.$store.commit({
//     type: "addCount",
//     n: 1
//   });
// },
// reset() {
//   this.$store.commit({
//     type: "resetCount",
//     data: 0
//   });
// },

// method3
// ...mapMutations({
//   theAdd: 'addCount',
//   theReset: 'resetCount'
// }),

// add () {
//   this.theAdd({n: 1})
// },
// reset () {
//   this.theReset({data: 0})
// }

效果一致。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值