我想知道是否有可能在全局等待中有条件地获取数据?
<script setup>
...
const test = ref([]);
if (myCondition) {
const {
data
} = await useAsyncData('test', () => $fetch('/my/api/call'));
test.value = data.value;
}
</script>
如果我这样写,测试值不是响应的,也不会在模板中更新
应该是这样的:
<script setup>
const myCondition = ref(false)
const test = ref()
watch(myCondition, async () => {
if (myCondition.value) {
const { data } = await useFetch('https://jsonplaceholder.typicode.com/posts/1')
test.value = data.value
} else {
test.value = undefined
}
})
</script>
<template>
<div>
<a @click="myCondition = !myCondition">Toggle!</a> <br />
{{ test }}
</div>
</template>
你也可以用test.value = $fetch(...)
代替useFetch
,但是这样会失去缓存。