📅 我們繼續 50 個小項目挑戰!—— Blurry Loading
組件
-
倉庫地址:https://github.com/SunACong/50-vue-projects
-
項目預覽地址:https://50-vue-projects.vercel.app/
? 組件目標
-
實現一個加載進度條,隨著加載進度的增加,背景圖像逐漸從模糊變清晰
-
展示一個百分比數字,表示當前的加載進度
-
整個過程無需外部庫,完全依賴 Vue3 和 Tailwind CSS
🧱 技術實現點
-
Vue3 的響應式狀態管理(ref)
-
使用 onMounted 和 onBeforeUnmount 生命周期鉤子管理定時器
-
Tailwind CSS 的 absolute、inset-0、bg-cover、bg-center 等布局類
-
動態綁定內聯樣式,實現模糊效果的漸變
🔧 BlurryLoading.vue 組件實現
<template><div class="relative h-screen w-screen"><div:style="{ filter: `blur(${blurPx}px)` }"class="absolute inset-0 bg-[url('https://images.unsplash.com/photo-1576161787924-01bb08dad4a4?auto=format&fit=crop&w=2104&q=80')] bg-cover bg-center bg-no-repeat"></div><div class="absolute inset-0 flex items-center justify-center"><div class="text-5xl font-bold text-gray-300">{{ loading }}%</div></div></div>
</template><script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'const loading = ref(0)
const blurPx = ref(30)let intervalonMounted(() => {interval = setInterval(() => {if (loading.value < 100) {loading.value += 2blurPx.value = 30 * (1 - loading.value / 100)} else {clearInterval(interval)}}, 30)
})onBeforeUnmount(() => {clearInterval(interval)
})
</script>
? 漸顯效果
ref
變量opacity
,根據loading.value
動態變化,隨著加載進度的推進從0
線性增長到1
。- 配合
transition-opacity duration-500
的 Tailwind 類,使背景圖從完全透明漸顯到完全不透明。 - 為任何元素設置
:style="{ opacity: xxx }"
配合 Tailwind 的過渡類,都可以實現漸顯。
💡 TailwindCSS 樣式重點講解
類名 | 功能描述 |
---|---|
absolute inset-0 | 使元素絕對定位并填滿父容器 |
bg-cover | 背景圖像覆蓋整個容器 |
bg-[url(xxx)] | 設置背景圖像 |
bg-center | 背景圖像居中顯示 |
bg-no-repeat | 背景圖像不重復 |
text-5xl | 設置字體大小為 5xl |
font-bold | 設置字體加粗 |
text-gray-300 | 設置字體顏色為灰色(300) |
🦌 常量定義 + 組件路由
constants/index.js
添加組件預覽常量:
export const projectList = [
{id: 5,title: 'Blurry Loading',image: 'https://50projects50days.com/img/projects-img/5-blurry-loading.png',link: 'BlurryLoading',}
]
router/index.js
中添加路由選項:
{path: '/BlurryLoading',name: 'BlurryLoading',component: () => import('@/projects/BlurryLoading.vue')
}
🚀 小結
這個組件展示了如何結合 Vue3 的響應式特性和 Tailwind CSS 的實用工具類,實現一個動態的加載效果。通過動態調整背景圖像的模糊程度,提升了用戶體驗。
📅 明日預告:Scroll Animation!實現滾動動畫組件。