vue 异步处理
A couple of months ago at work, we’ve decided to go all-in on Composition API with a new version of our product.
几个月前,我们决定使用新版本的产品全面使用Composition API。
And from what I can tell — looking around at new plugins appearing, all the discussions in the discord community — the composition API gets increasingly more popular. It’s not just us.
据我所知-环顾四周出现的新插件,以及不和谐社区中的所有讨论-composition API越来越受欢迎。 不只是我们
Composition API makes a lot of things easier but it also brings some challenges as some things need to be rethought regarding how they fit into this new concept and it might take some time before the best practices are established.
Composition API使很多事情变得更容易,但同时也带来了一些挑战,因为需要重新考虑如何使它们适应这个新概念,并且可能需要一些时间才能建立最佳实践。
One of the challenges is managing state, especially when asynchrony is involved.
挑战之一是管理状态,尤其是在涉及异步时。
I’ll try to showcase different approaches for this, including vue-concurrency, which I’ve created and that I maintain.
我将尝试展示不同的方法,包括我创建并维护的vue-concurrency 。
管理异步状态 (Managing async state)
You might ask what’s there to manage? Composition API is flexible enough, this shouldn’t be a problem.
您可能会问要管理什么? Composition API足够灵活,这不应该成为问题。
The most typical asynchronous operation is doing an AJAX request to the server. In the past years, some generic issues of AJAX have been solved or mitigated. The callback hell was extinguished with Promises and those were later sugared into async/await. Async/await is pretty awesome and the code is a joy to read compared to the original callback hell spaghetti that was often written years before.
最典型的异步操作是对服务器执行AJAX请求。 在过去的几年中,AJAX的一些通用问题已得到解决或缓解。 回调地狱已被Promises扑灭,后来被塞入异步/等待状态。 与多年前编写的原始回调地狱意大利面条相比,Async / await非常棒,并且代码令人愉悦。
But the fact, that things are much better now doesn’t mean that there’s no more space for improvement.
但是事实是,现在情况好得多,并不意味着没有更多的改进空间。
异步功能/承诺不跟踪状态 (Async function / Promises don’t track state)
When you work with a promise, there’s a promise.then
, promise.catch
,promise.finally
and that’s it. You cannot accessstatus
or someisPending
property and other state properties. That’s why you often have to manage this state yourself and with Composition API, your code might look like this:
当您兑现承诺时,就有了一个promise.then
, promise.catch
, promise.finally
就是这样。 您无法访问status
或某些isPending
属性和其他状态属性。 这就是为什么您经常不得不自己管理这种状态的原因,并且使用Composition API,您的代码可能如下所示:
import { ref } from 'vue';
export default defineComponent({
setup() {
const isLoading = ref(false);
const error = ref(null);
const data = ref(null);
const getUsers = async () => {
isLoading.value = true;
try {
const json = await axios('foo/bar');
data.value = json;
isLoading.value = false;
} catch (e) {
error.value = e;
}
};
return { isLoading, error, data, getUsers };
}
});
<template>
<div>
<div v-if="isLoading"> Loading ... </div>
<div v-else="error"> {
{ error.message }} <button @click="getUsers">try again</button> </div>
<div v-else> {
{ data }} </div>
</div>
</template>
Here we pass refs like isLoading
error
data
to the template. getUsers
functio