vuex:Promise与Action的“爱恨情仇”

都知道Vue中,或者准确地说是vuex中,action是异步函数(表现为actions中的函数),但我们怎么知道他们已经完成了呢?

用过vuex的我们可能一时间想到了【观察计算属性的改变】的方法,但这不够理想。
其实我们有更好的办法:在action中返回一个promise对象

另外,调用dispatch也会返回一个promise对象。运用它就可以在action运行结束时去运行其他代码 —— 比如:loading。

比如:

actions:{
	getMessages({commit}){
		return fetch('/api/new-messages')
				.then((res)=>res.json())
				.then((data)=>{
					if(data.messages.length){
						commit('addMessage',data.messages);   //往mutation里发通知
					}
				});
	}
}

上面代码较之前改动很小 —— 只是在fetch前加了一个return。

或者,我们可以这样玩:

import { mapState } from 'vuex';

const MxcCount={
	template:`<p>
				Message:{{message.length}}
				<span v-if="loading">(updating...)</span>
				<a v-else @click.prevent="handleUpdate">(update)</a>
			  </p>`,
	data:()=>({
		updating:false
	}),
	computed:mapState(['message']),
	methods:{
		this.updating=true;
		this.$store.dispatch('getMessages')
			.then(()=>{
				this.updating=false;
			});
	}
};
发布了195 篇原创文章 · 获赞 391 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_43624878/article/details/103911682