vue3 圖片輪播效果實(shí)現(xiàn):仿 fortnite.gg 風(fēng)格
本文介紹如何在vue3中實(shí)現(xiàn)類似Fortnite.gg商城頁面圖片自動(dòng)切換的輪播效果,尤其針對(duì)商品圖片數(shù)量不定的情況。
需求分析
目標(biāo)是創(chuàng)建一個(gè)Vue3組件,能夠自動(dòng)輪播商品圖片。每個(gè)商品可能擁有數(shù)量不等的圖片,組件需要靈活適應(yīng)。 我們希望實(shí)現(xiàn)平滑的圖片切換動(dòng)畫。
實(shí)現(xiàn)方案
我們將采用css動(dòng)畫和z-index屬性來控制圖片的顯示和切換。 通過改變z-index值,實(shí)現(xiàn)圖片層級(jí)的變化,并配合CSS動(dòng)畫,達(dá)到流暢的過渡效果。
代碼示例
以下代碼片段展示了組件的核心邏輯:
立即學(xué)習(xí)“前端免費(fèi)學(xué)習(xí)筆記(深入)”;
<template> <div class="shop-card" v-for="item in items" :key="item.id"> <div class="image-container"> @@##@@ </div> <div class="item-info-container"> <p class="item-name">{{ item.name }}</p> <p class="item-price">@@##@@{{item.price}}</p> </div> </div> </template> <script> export default { data() { return { currentIndex: 0, }; }, mounted() { setInterval(() => { this.currentIndex = (this.currentIndex + 1) % this.item.images.length; }, 3000); // 每3秒切換一次 }, }; </script> <style scoped> .image-container { position: relative; width: 200px; /* 調(diào)整圖片容器寬度 */ height: 150px; /* 調(diào)整圖片容器高度 */ overflow: hidden; } .item-image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; opacity: 0; transition: opacity 0.5s ease-in-out; /* 添加平滑過渡動(dòng)畫 */ } .item-image.active { opacity: 1; z-index: 1; /* 設(shè)置當(dāng)前顯示圖片的 z-index */ } </style>
這段代碼利用v-for循環(huán)渲染每張圖片,并使用:class=”{ active: currentIndex === index }”綁定類名來控制圖片的顯示狀態(tài)。 :style=”{ zIndex: index }” 確保圖片按照順序疊加,currentIndex變量控制當(dāng)前顯示的圖片索引,setInterval函數(shù)實(shí)現(xiàn)自動(dòng)切換。 CSS樣式確保圖片填充容器并添加平滑過渡動(dòng)畫。
此方法避免了復(fù)雜的遮罩動(dòng)畫,通過簡(jiǎn)單的CSS和Vue3特性實(shí)現(xiàn)了圖片輪播效果,并能有效適應(yīng)不同數(shù)量的商品圖片。 您可以根據(jù)實(shí)際需求調(diào)整圖片容器尺寸和動(dòng)畫時(shí)長(zhǎng)。