Vue3 Script Setup实现点击仅展示单条随机Quote的方法
实现Vue3随机单条Quote生成器
当前你遇到的问题是点击按钮后会展示所有Quote,要改成每次仅显示一条随机Quote,我们可以通过以下步骤修改代码:
原代码问题点
- 用
v-for遍历所有数据,导致显示全部内容 getData函数里的随机索引计算错误(误用了api.length,但api是fetch响应对象,不是数据数组)- 对
finalApi的取值逻辑错误(它是普通数组,不需要.value)
修改方案
- 调整响应式变量:不再用
listItems存储所有数据,改用currentQuote存储当前要显示的单条Quote - 修正
getData函数:获取数据后生成随机索引,从数组中取出对应项赋值给currentQuote - 修改模板:移除
v-for,直接渲染currentQuote的属性,并添加存在性判断避免空值报错
修改后的完整代码
<template> <div class="about"> <div> <h1 class="mb-6">This is a random Blog page</h1> </div> <!-- 只有当currentQuote存在时才渲染内容 --> <div v-if="currentQuote" class="justify-center flex flex-column text-center"> <h5> ID: {{ currentQuote.id }}</h5> <h2> Title: {{ currentQuote.title }}</h2> <h3> Body: {{ currentQuote.body }}</h3> </div> <!-- 初始状态提示 --> <div v-else class="text-center"> <p>点击按钮获取随机博客</p> </div> <button @click="getData()" class="bg-orange-500">Get a new blog</button> </div> </template> <script setup> import { ref } from 'vue' // 存储当前显示的单条数据,初始为空 const currentQuote = ref(null) async function getData() { const response = await fetch('https://jsonplaceholder.typicode.com/posts') const allQuotes = await response.json() // 生成合法范围内的随机索引 const randomIndex = Math.floor(Math.random() * allQuotes.length) // 赋值随机选中的Quote currentQuote.value = allQuotes[randomIndex] } </script>
补充优化建议
如果不想每次点击都重新请求API,可以把数据缓存起来,只在组件初始化时请求一次,之后直接从本地数组随机选取:
<script setup> import { ref, onMounted } from 'vue' const currentQuote = ref(null) const allQuotes = ref([]) // 初始化时获取一次所有数据 onMounted(async () => { const response = await fetch('https://jsonplaceholder.typicode.com/posts') allQuotes.value = await response.json() }) function getRandomQuote() { if (allQuotes.value.length === 0) return const randomIndex = Math.floor(Math.random() * allQuotes.value.length) currentQuote.value = allQuotes.value[randomIndex] } </script>
模板里的按钮点击事件改成@click="getRandomQuote"即可。
内容的提问来源于stack exchange,提问作者tocajossan
相关产品推荐
相关产品推荐

