vue3的轮播图怎么写
时间: 2023-07-28 14:24:18 浏览: 194
您好,要实现Vue3的轮播图,可以使用Vue3的组合式API和CSS3的transition动画效果。以下是一个示例:
```html
<template>
<div class="slider-container">
<ul class="slider-list" :style="{ transform: 'translateX(' + translateX + 'px)' }">
<li v-for="(item, index) in sliderItems" :key="index" class="slider-item">{{ item }}</li>
</ul>
</div>
</template>
<script>
import { ref, watch, nextTick } from 'vue'
export default {
setup() {
const sliderItems = ref(['item1', 'item2', 'item3', 'item4']) // 轮播项
const currentIndex = ref(0) // 当前轮播项的索引
const translateX = ref(0) // 轮播项的偏移量
// 轮播动画
const slide = (nextIndex) => {
if (nextIndex < 0 || nextIndex >= sliderItems.value.length) {
return
}
const sliderWidth = document.querySelector('.slider-container').clientWidth // 轮播容器宽度
translateX.value = -(nextIndex * sliderWidth) // 计算偏移量
currentIndex.value = nextIndex // 更新当前索引
}
// 自动轮播
const autoSlide = () => {
setInterval(() => {
const nextIndex = (currentIndex.value + 1) % sliderItems.value.length
slide(nextIndex)
}, 3000)
}
// 监听currentIndex的变化,实现轮播效果
watch(currentIndex, (newValue, oldValue) => {
const sliderWidth = document.querySelector('.slider-container').clientWidth // 轮播容器宽度
const distance = (newValue - oldValue) * sliderWidth
nextTick(() => {
document.querySelector('.slider-list').style.transition = 'transform .5s linear'
translateX.value -= distance
// 监听transition动画结束事件
document.querySelector('.slider-list').addEventListener('transitionend', () => {
document.querySelector('.slider-list').style.transition = ''
if (currentIndex.value >= sliderItems.value.length) { // 处理循环轮播
translateX.value = 0
currentIndex.value = 0
}
})
})
})
autoSlide()
return {
sliderItems,
currentIndex,
translateX
}
}
}
</script>
<style>
.slider-container {
width: 100%;
overflow: hidden;
}
.slider-list {
display: flex;
transition: transform .5s linear;
}
.slider-item {
flex: 1;
height: 200px;
text-align: center;
line-height: 200px;
font-size: 24px;
}
</style>
```
这是一个简单的轮播图实现,具有自动轮播、循环轮播等功能。您可以根据需要进行修改和优化。
阅读全文