如何在Vue Options API中正确使用VueUse的computedAsync?
在Options API风格的Vue组件中使用VueUse的正确方式
当然可以在Options API中使用VueUse,但你的写法存在两个核心问题,导致渲染异常:
- Options API的computed getter会重复创建computedAsync实例:
每次组件渲染时,computed里的vendorsgetter都会执行,每次都新建一个computedAsync,这会触发多次异步请求,也是你看到重复数组的原因。 - 错误地在computed中返回Ref对象:
computedAsync返回的是一个Ref对象,而Options API的computed应该返回原始值。直接返回Ref会让模板接收到Ref内部的状态变化(包括加载过程中的中间状态false/true),这就是输出里出现奇怪布尔值的原因。
解决方案一:在created钩子中初始化computedAsync
把computedAsync的创建移到created钩子中,挂载到组件实例上,避免重复创建:
import { computedAsync } from '@vueuse/core' export default defineComponent({ name: "VendorsList", data() { return { vendorsRef: null } }, created() { // 只在组件创建时初始化一次computedAsync this.vendorsRef = computedAsync( async () => await stock(db), [] // 默认值 ) }, // 可选:保持原有vendors属性名,通过computed解包Ref computed: { vendors() { return this.vendorsRef?.value || [] } } })
模板中直接使用vendors即可:
<div v-for="vendor in vendors" class=""> <pre>{{ JSON.stringify(vendor, null, 4)}}</pre> --------------- </div>
解决方案二:使用useAsyncState更适配异步场景
如果只是需要获取异步数据,VueUse的useAsyncState更适合Options API,它会直接返回数据和加载状态:
import { useAsyncState } from '@vueuse/core' export default defineComponent({ name: "VendorsList", data() { return { vendors: [], isLoading: false } }, created() { const { state, isLoading } = useAsyncState( () => stock(db), // 异步函数 [] // 默认值 ) // 将Ref挂载到组件实例,模板会自动解包 this.vendors = state this.isLoading = isLoading } })
模板中还能添加加载状态提示:
<div v-if="isLoading">加载中...</div> <div v-else v-for="vendor in vendors" class=""> <pre>{{ JSON.stringify(vendor, null, 4)}}</pre> --------------- </div>
内容的提问来源于stack exchange,提问作者angelcervera
相关产品推荐
相关产品推荐

