我很困惑。我想要一个简单的通用获取函数来学习它的基础知识,但我想使用 Vue Composition API 和脚本设置来完成它。
这是我的脚本:
<script setup>
import {ref} from 'vue';
const boredInfo = ref(null)
function theData(url) {
fetch(url)
.then(response => response.json())
.then(actualData => {
console.log(actualData)
boredInfo.value = actualData
})
.catch((e) => {
console.error('Das ist der Catch Error: ', e)
})
return boredInfo
}
theData('https://www.boredapi.com/api/activity')
</script>
这是我的模板
<template>
<h1>Lets go!</h1>
<div>
<h1>Aktivität: {{boredInfo.activity}}</h1>
</div>
</template>
我得到的错误:
ypeError: Cannot read properties of null (reading 'activity')
我得到的 JSON
{
"activity": "Make your own LEGO creation",
"type": "recreational",
"participants": 1,
"price": 0,
"link": "",
"key": "1129748",
"accessibility": 0.1
}
就这么简单...在整个互联网上我找不到脚本设置、Fetch API 和显示值的解决方案。
但最令人困惑的是:它显示了值(value)!那么为什么会出现这个错误呢?
最佳答案
问题是您在获取完成之前访问 boredInfo.activity
,此时 boredInfo
仍然只是 ref(null)
。
使用预期的结构初始化它,即
const boredInfo = ref({activity: null})
或者使用v-if
避免过早访问,表达式中的三元组,可选链接(?.
)等。类似:
<h1 v-if="boredInfo !== null">Aktivität: {{boredInfo.activity}}</h1>
您可以在加载时显示加载微调器,这总是很好。
关于vue.js - 使用 Vue Composition API 获取 API(脚本设置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75687152/