Vuex-状态管理模式-核心概念3-actions

Vuex-核心概念3—actions

mutations 中是同步代码,要操作异步代码则要在 actions 中


如果在 mutations 中有进行异步操作,那么页面会刷新,但数据不会在 state 对象中改变


Vuex-状态管理的目录结构,转战Vuex 状态管理模式-项目结构
Vuex-核心概念1,转战state+getters
Vuex-核心概念2,转战mutations
Vuex-核心概念4,转战modules

1、错误代码示例
state: {
	info: {
		name: 'Tom',
		age: 100,
		height: 1.92
	}
},
mutations: {
	updateInfo (state) {
		state.info.name = 'Jery'
		// 错误写法
		//setTimeOut(() => {
		//	state.info.name = 'Jery'
		//})
	}
}
2、要在 actions 中处理异步代码
/*
* context:上下文,相当于 state
*/
actions: {
	aUpdateInfo (context) {
		setTimeOut(() => {
			context.commit('updateInfo')
		}, 1000)
	}
}
  • 组件中使用,使用方法 this.$store.dispatch
methods: {
	aUpdateInfoAdd () {
		this.$store.dispatch('aUpdateInfo ')
	}
}
3、如果调用了异步操作后,需要异步代码返回一个结果,告诉调用的地方已经完成了异步操作,可以对返回结果进行一些处理

使用 Promise()

actions: {
	aUpdateInfo (context, payload) {
		// 把异步操作放到 Promise () 中
		return new Promise((resolve, reject) => {
			setTimeOut(() => {
				// 调用 mutations
				context.commit('updateInfo')
				
				resolve(111) // 成功的回调,then() 
			}, 1000)
		})
	}
}
  • 组件中使用
<h2>{{$store.state.info}}</h2>
<button @click="aUpdateInfoAdd">修改信息</button>

<script>
export default {
	methods: {
		aUpdateInfoAdd () {
			this.$store.dispatch('aUpdateInfo').then(res => {
				console.log('异步操作已经完成')
				console.log(res) // 111
			})
		}
	}
}
</script>

——————————————————————————————
“连太阳都没法做到让每个人满意,何况我只是一枚小小的人儿啊 ”

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值