VueX学习笔记(actions)

VueX中的Actions用于处理异步操作,组件通过$store.dispatch调用,然后通过commit传递给mutations来更新state。本文介绍了Actions的基本定义及如何结合Promise在Actions中进行异步操作。
摘要由CSDN通过智能技术生成

Actions的基本定义

Actions是用来对异步操作的VueX

  • 组件中通过$store.dispatch传给actions

  • actions 通过commit提交给mutations

  • mutations直接修改state

components中:

<button @click="updateInfo('you')">修改信息</button>

methods

updateInfo(name) {
	this.$store.dispatch('upinfo', name)
}

store/index.js

state:{
	info:{
		name: 'zhiou',
		age: 18,
		height: 1.89
	}
}
actions:{
	aUpdataInfo(context, name) {
		setTimeout(() => {
			context.commit('upinfo', name)
		}, 1000)
	}
}
mutations:{
	upinfo(state, name){
		state.info.name = name
	}
}

Actions中使用Promise

store/index.js

actions:{
	aUpdataInfo(context, name) {
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				context.commit('upinfo', name)
				resolve('传递成功!')
			}, 1000)
		})
	}
}

components中的methods

methods:{
	updateInfo(name) {
		this.$store.dispatch('aUpdataInfo', name)
		.then(console.log('提交成功!'))
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值