返回
Vue 3 封装轮播图组件:轻量、高效、自定义
前端
2024-01-12 05:58:23
在现代 Web 开发中,轮播图是一种常见的交互元素,它可以用于展示产品、服务、新闻等各种类型的视觉内容。在 Vue 3 中,我们可以通过封装一个自定义组件的方式,轻松实现功能丰富且易于使用的轮播图。
首先,我们定义轮播图组件的基本结构:
<template>
<div class="carousel">
<div class="carousel-inner">
<slot />
</div>
<div class="carousel-controls">
<button class="carousel-control-prev" @click="prev">
<i class="fas fa-chevron-left"></i>
</button>
<button class="carousel-control-next" @click="next">
<i class="fas fa-chevron-right"></i>
</button>
</div>
<div class="carousel-indicators">
<button class="carousel-indicator" v-for="item, index in slides" :key="index" @click="goTo(index)">
{{ index + 1 }}
</button>
</div>
</div>
</template>
在模板中,我们定义了轮播图的基本结构,包括轮播图容器、轮播图内容区域、轮播图控制按钮和轮播图指示器。
然后,我们在脚本部分定义组件的逻辑:
<script>
import { ref, computed, watch } from 'vue'
export default {
name: 'Carousel',
props: {
interval: {
type: Number,
default: 5000
},
animation: {
type: String,
default: 'fade'
},
pauseOnHover: {
type: Boolean,
default: true
}
},
setup(props) {
const slides = ref([])
const currentIndex = ref(0)
const timer = ref(null)
watch(currentIndex, (newValue, oldValue) => {
if (oldValue !== newValue) {
clearTimeout(timer.value)
timer.value = setTimeout(() => {
next()
}, props.interval)
}
})
const prev = () => {
currentIndex.value = (currentIndex.value - 1 + slides.value.length) % slides.value.length
}
const next = () => {
currentIndex.value = (currentIndex.value + 1) % slides.value.length
}
const goTo = (index) => {
currentIndex.value = index
}
return {
slides,
currentIndex,
timer,
prev,
next,
goTo
}
},
mounted() {
this.slides = this.$slots.default()
this.timer = setTimeout(() => {
this.next()
}, this.interval)
if (this.pauseOnHover) {
this.$el.addEventListener('mouseenter', () => {
clearTimeout(this.timer)
})
this.$el.addEventListener('mouseleave', () => {
this.timer = setTimeout(() => {
this.next()
}, this.interval)
})
}
},
beforeUnmount() {
clearTimeout(this.timer)
}
}
</script>
在脚本部分,我们定义了组件的属性、状态和方法。其中,slides 状态用于存储轮播图的内容,currentIndex 状态用于存储当前显示的轮播图索引,timer 状态用于存储轮播图自动播放的定时器。
我们还定义了 prev、next 和 goTo 方法,用于控制轮播图的播放。prev 方法用于播放上一张轮播图,next 方法用于播放下一张轮播图,goTo 方法用于跳转到指定索引的轮播图。
在 mounted 钩子函数中,我们获取轮播图的内容并启动轮播图的自动播放。在 beforeUnmount 钩子函数中,我们停止轮播图的自动播放。
最后,我们可以通过在模板中使用 carousel 组件来实现轮播图:
<template>
<carousel>
<div class="carousel-item">
<img src="image1.jpg" alt="Image 1">
</div>
<div class="carousel-item">
<img src="image2.jpg" alt="Image 2">
</div>
<div class="carousel-item">
<img src="image3.jpg" alt="Image 3">
</div>
</carousel>
</template>
这样,我们就完成了一个 Vue 3 轮播图组件的封装,该组件轻量、高效且可自定义,可以满足各种场景下的使用需求。