如何在 vue3 脚本设置中显示一个报价而不是所有 API?

how do I get one quote to show instead of all API in vue3 script setup?

提问人:tocajossan 提问时间:11/25/2022 更新时间:11/25/2022 访问量:25

问:

js 和 Im 使用组合 API 进行脚本设置。我正在做一个简单的报价生成器并获取 API。只是当我按下按钮时,我会显示所有报价。我怎样才能做到当时只显示一个随机报价?

<template>
  <div class="about">
  <div>
    <h1 class="mb-6">This is a random Blog page</h1>
  </div>
  <div v-for="quote in listItems" class="justify-center flex flex-column text-center">
    <h5> ID: {{ quote.id }}</h5>
    <h2> Title: {{ quote.title }}</h2>
    <h3> Body: {{ quote.body }}</h3>
  </div>
  <button @click="getData()" class="bg-orange-500">Get a new blog</button>
  </div>

</template>

<script setup>
import {ref} from 'vue'
let id = ref(0)
let title = ref('hallo')
let body = ref('random blogs')
const listItems = ref([])

async function getData(){
  const api = await fetch('https://jsonplaceholder.typicode.com/posts')
  const finalApi = await api.json()
  listItems.value = finalApi
  const index = Math.floor(Math.random()*api.length)
  const quoteOfTheDay = finalApi.value[index]
  quoteOfTheDay.value = quoteOfTheDay.body
 
  
}
</script>
vue.js 随机 提取 报价

评论


答:

1赞 bassxzero 11/25/2022 #1

您将遍历模板中的所有 api 响应。相反,只显示一个。

<template>
  <div class="about">
  <div>
    <h1 class="mb-6">This is a random Blog page</h1>
  </div>
  <div v-if="quote" class="justify-center flex flex-column text-center">
    <h5> ID: {{ quote.id }}</h5>
    <h2> Title: {{ quote.title }}</h2>
    <h3> Body: {{ quote.body }}</h3>
  </div>
  <button @click="getData()" class="bg-orange-500">Get a new blog</button>
  </div>

</template>

<script setup>
import {ref} from 'vue'
let id = ref(0)
let title = ref('hallo')
let body = ref('random blogs')
const listItems = ref([])

let quote = ref(null)

async function getData(){
  const api = await fetch('https://jsonplaceholder.typicode.com/posts')
  const finalApi = await api.json()
  const index = Math.floor(Math.random() * finalApi.length)
  quote.value = finalApi[index]
  
}
</script>

评论

0赞 tocajossan 11/25/2022
谢谢你的回答,但我收到一个错误;AboutView.vue:28 Uncaught (in promise) TypeError:无法读取 getData 中未定义的属性(读取“NaN”)