iT邦幫忙

0

Vue3 <script setup> fetch 無法顯示資料

新手請教:
我抓的到資料 也能console.log出來 想把資料放到網頁上 但在網頁上無法顯示 請問該怎麼解決?

https://ithelp.ithome.com.tw/upload/images/20220127/20122444NJ254Ir7rd.png

<script setup>
  const response = await fetch("https://api.kcg.gov.tw/Api/Service/Get/9c8e1450-e833-499c-8320-29b36b7ace5c").then(res=>res.text());
  console.log(response);
</script>

<template>
  <div>{{ response }}</div>
</template>

<style scoped>

</style>

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
cloudeasy
iT邦新手 5 級 ‧ 2022-01-27 03:28:05
最佳解答

在 script setup 裡面使用 await, 需要搭配 Suspense 使用
https://v3.vuejs.org/guide/migration/suspense.html#suspense

但 Suspense 還在實驗階段

可以改成

<script setup>
  import { ref } from 'vue'
  const response = ref('')
  fetch("https://api.kcg.gov.tw/Api/Service/Get/9c8e1450-e833-499c-8320-29b36b7ace5c").then(async res=> {
    response.value = await res.text()
  })
</script>

<template>
  <div>{{ response }}</div>
</template>

<style scoped>

</style>

或者寫在 hook

<script setup>
  import { ref, onBeforeMount } from 'vue'
  const response = ref('')
  onBeforeMount(async () => {
    response.value = await fetch("https://api.kcg.gov.tw/Api/Service/Get/9c8e1450-e833-499c-8320-29b36b7ace5c").then(async res=> res.text())
  })
  
</script>

<template>
  <div>{{ response }}</div>
</template>

<style scoped>

</style>

參考官方文件:
https://v3.vuejs.org/api/sfc-script-setup.html#reactivity

adha9990 iT邦新手 5 級 ‧ 2022-01-27 05:02:33 檢舉

成功了!感謝

我要發表回答

立即登入回答