我有一个类Thing
,它的构造函数启动异步fetch
操作.fetch
完成后,结果将分配给Thing
对象上的字段:
class Thing {
constructor() {
this.image = null
this.load()
}
async load() {
const response = await fetch('https://placekitten.com/200/300')
const blob = await response.blob()
this.image = await createImageBitmap(blob)
}
}
我在Vue
组件中使用thing.image
.问题是,当Promise
解决时,Vue无法识别image
中的变化.我想我理解为什么会发生这种情况:在构造函数中,this
指的是原始Thing
,而不是Vue的react 式代理包装器.因此,对this.image
的赋值最终绕过了代理.
如果我将load
调用移出构造函数,那么它就可以工作,因此load
函数中的this
引用了react 式代理.但这让我的Thing
课更难使用.
有没有更好的方法来处理这个问题?
最小示例(Vue playground link):
<script setup>
import { reactive } from 'vue'
class Thing {
constructor() {
this.image = null
this.load() // This does not trigger reactivity.
}
async load() {
const response = await fetch('https://placekitten.com/200/300')
const blob = await response.blob()
this.image = await createImageBitmap(blob)
}
}
const thing = reactive(new Thing())
// thing.load() // This triggers reactivity as expected.
</script>
<template>
<p v-if="thing.image">
Image size is {{thing.image.width}}×{{thing.image.height}}
</p>
<p v-if="!thing.image">
Loading...
</p>
</template>