<template>
  <div class="carousel">
    <div class="carousel-inner" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
      <div class="carousel-item" v-for="(image, index) in images" :key="index">
        <img :src="image" alt="轮播图" />
      </div>
    </div>
    <div class="carousel-controls">
      <button @click="prev">‹</button>
      <button @click="next">›</button>
    </div>
    <div class="carousel-indicators">
      <span
        v-for="(image, index) in images"
        :key="index"
        :class="{ active: index === currentIndex }"
        @click="goTo(index)"
      ></span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const images = [
  'https://image.so.com/ai/s?q=%E5%B9%B3%E5%8F%B0%E5%9B%BE%E7%89%87&listsrc=sobox&listsign=28c4844d972744afe424ff0172e943a0&src=360pic_strong',
  'https://via.placeholder.com/800x400?text=Slide+2',
  'https://via.placeholder.com/800x400?text=Slide+3',
  'https://via.placeholder.com/800x400?text=Slide+4',
];

const currentIndex = ref(0);
const intervalTime = 3000; 
let timer = null;


const next = () => {
  currentIndex.value = (currentIndex.value + 1) % images.length;
};


const prev = () => {
  currentIndex.value = (currentIndex.value - 1 + images.length) % images.length;
};


const goTo = (index) => {
  currentIndex.value = index;
};


onMounted(() => {
  timer = setInterval(() => {
    next();
  }, intervalTime);
});


onUnmounted(() => {
  clearInterval(timer);
});
</script>

<style scoped>
.carousel {
  position: relative;
  width: 800px;
  height: 400px;
  overflow: hidden;
  margin: 0 auto;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.carousel-inner {
  display: flex;
  transition: transform 0.5s ease;
}

.carousel-item {
  min-width: 100%;
  box-sizing: border-box;
}

.carousel-item img {
  width: 220px;
  height: 220px;
  object-fit: cover;
}


.carousel-controls {
  position: absolute;
  top: 50%;
  width: 100%;
  display: flex;
  justify-content: space-between;
  transform: translateY(-50%);
}

.carousel-controls button {
  background: rgba(0, 0, 0, 0.5);
  border: none;
  color: #fff;
  font-size: 2rem;
  padding: 10px 15px;
  cursor: pointer;
  border-radius: 50%;
  transition: background 0.3s;
}

.carousel-controls button:hover {
  background: rgba(0, 0, 0, 0.7);
}

/* 底部指示器 */
.carousel-indicators {
  position: absolute;
  bottom: 15px;
  left: 50%;
  display: flex;
  transform: translateX(-50%);
}

.carousel-indicators span {
  display: inline-block;
  width: 12px;
  height: 12px;
  margin: 0 5px;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 50%;
  cursor: pointer;
  transition: background 0.3s;
}

.carousel-indicators span.active {
  background: rgba(255, 255, 255, 1);
}
</style>
