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

Time:11-25

js and Im using composition API with script setup. Im doing a simple quote generator and fetching API. Its just that I get ALL quotes to show when I press the button. How can I do so only one random quote shows at the time?

<template>
  <div >
  <div>
    <h1 >This is a random Blog page</h1>
  </div>
  <div v-for="quote in listItems" >
    <h5> ID: {{ quote.id }}</h5>
    <h2> Title: {{ quote.title }}</h2>
    <h3> Body: {{ quote.body }}</h3>
  </div>
  <button @click="getData()" >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>

CodePudding user response:

You're looping through all the api responses in your template. Instead just display one.

<template>
  <div >
  <div>
    <h1 >This is a random Blog page</h1>
  </div>
  <div v-if="quote" >
    <h5> ID: {{ quote.id }}</h5>
    <h2> Title: {{ quote.title }}</h2>
    <h3> Body: {{ quote.body }}</h3>
  </div>
  <button @click="getData()" >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>
  • Related