50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | Dad Jokes(冷笑话卡片)

发布于:2025-06-04 ⋅ 阅读:(27) ⋅ 点赞:(0)

📅 我们继续 50 个小项目挑战!—— DadJokes 组件

在这里插入图片描述

豆包翻译确实可以,冷笑话应该属于各类语言比较难理解的风格,这里豆包自动解析出了其中的含义。确实不错!!!


😂 组件目标

构建一个轻量有趣的“Dad Jokes”组件,点击按钮即可获取一个随机冷笑话,用于放松心情、提升用户体验,也适合嵌入仪表盘或侧边栏作为互动装饰组件。

🛠️ 技术实现点

  • 使用 Vue3 的 <script setup> 写法,逻辑清晰简洁。
  • 使用 fetch 请求公开 API(https://icanhazdadjoke.com)。
  • 使用 TailwindCSS 快速搭建居中卡片样式,提升视觉层次感。
  • 使用响应式变量 ref 和基础的异步请求逻辑。

🧱 组件实现

<template>
    <div class="flex h-screen items-center justify-center">
        <div class="flex w-xl flex-col items-center justify-center gap-20 rounded-2xl bg-white p-8">
            <h3 class="text-xl font-bold text-gray-600">Don't Laugh Challenge</h3>
            <div id="joke" class="text-2xl">{{ joke }}</div>
            <button class="btn bg-blue-500 hover:bg-blue-300" @click="getJoke">
                Get Another Joke
            </button>
        </div>
    </div>
</template>


🤖 API 说明

<script setup>
import { ref } from 'vue'

const joke = ref('')

async function getJoke() {
    const config = {
        headers: {
            Accept: 'application/json',
        },
    }

    try {
        const response = await fetch('https://icanhazdadjoke.com', config)
        const data = await response.json()
        joke.value = data.joke
    } catch (error) {
        console.error('Error fetching joke:', error)
        joke.value = 'Failed to load joke. Try again!'
    }
}

// 初始化时获取第一个笑话
getJoke()
</script>
  • https://icanhazdadjoke.com

    • 免费公开的 dad joke API。
    • 通过设置 Accept: application/json 头即可返回 JSON 格式。

💡 用户交互亮点

  • 初次进入页面即展示一个冷笑话,避免“空白页面”冷场。
  • 每次点击按钮即可刷新笑话,交互直接。
  • 响应式变量自动更新视图,无需刷新页面。

🎨 TailwindCSS 样式重点

类名 说明
flex items-center justify-center 实现页面居中对齐
w-xl p-8 rounded-2xl bg-white 卡片容器样式,居中圆角白底
text-xl font-bold text-gray-600 标题样式
text-2xl 笑话正文文字
bg-blue-500 hover:bg-blue-300 按钮颜色及悬停状态

🧾 常量定义 + 组件路由建议

constants/index.js 添加组件预览常量:

export const projectList = [
{
        id: 10,
        title: 'Dad Jokes',
        image: 'https://50projects50days.com/img/projects-img/10-dad-jokes.png',
        link: 'DadJokes',
    },
]

router/index.js 中添加路由选项:


    {
        path: '/DadJokes',
        name: 'DadJokes',
        component: () => import('@/projects/DadJokes.vue'),
    },

🧾总结

此组件非常适合嵌入到:

  • 🎯 仪表盘(Dashboard):增加轻松氛围
  • 🧩 首页右栏 / 抽屉组件:作为彩蛋趣味功能
  • 👨‍💻 项目加载页:等待时读笑话减压


👉 下一篇,我们将完成 EventKeyCodes组件,一个可以显示用户按下的键盘按键信息!🚀


网站公告

今日签到

点亮在社区的每一天
去签到