先上效果图
完整代码
<script setup lang="ts">
import {
ref, defineProps} from "vue";
// 定义组件属性
const props = defineProps({
list: {
// 要轮播的图片的数组
type: Array as () => Array<Object>,
required: true,
default: () => {
return []
}
}
})
// 当前显示的图片在list数组中的下标
let active = ref<number>(1)
// 定时器
let timer: any = null;
// 开始轮播
const startCarousel = (): void => {
if (timer) return
timer = setInterval(() => {
if (active.value >= props.list.length) {
active.value = 1
return
}
active.value++
}, 1000)
}
// 停止轮播
const stopCarousel = (): void => {
clearInterval(timer)
timer = null
}
// 上一张
const pre = (): void => {
if (active.value === 1) {
active.value = props.list.length
return
}
active.value--
}
// 下一张
const next = (): void => {
if(active.value === props.list.length){
active.value = 1
return
}
active.value++
}
startCarousel()
</script>
<template>