vue2实现轮播图

1.在components路径下新建文件Carousel.vue,在Carousel.vue文件中创建一个 Vue 组件实现轮播图的功能

<script>
export default {
  data() {
    return {
      currentIndex: 0,
      items: [
        require('../assets/logo.png'),
        require('../assets/logo.png'),
      ],
      interval: null
    };
  },
  computed: {
    carouselStyle() {
      return {
        transform: `translateX(-${this.currentIndex * 100}%)`,
        transition: 'transform 0.5s ease-in-out'
      };
    }
  },
  methods: {
    prev() {
      this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length;
    },
    next() {
      this.currentIndex = (this.currentIndex + 1) % this.items.length;
    },
    goToIndex(index) {
      this.currentIndex = index;
    },
    startAutoplay() {
      this.interval = setInterval(() => {
        this.next();
      }, 3000);
    },
    stopAutoplay() {
      clearInterval(this.interval);
    }
  },
  mounted() {
    this.startAutoplay();
  },
  beforeDestroy() {
    this.stopAutoplay();
  }
};
</script>

<style scoped>
.carousel {
  position: relative;
  width: 100%;
  overflow: hidden;
}

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

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

.carousel-image {
  width: 100%;
  display: block;
}

.carousel-control {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  border: none;
  cursor: pointer;
  padding: 10px;
  font-size: 18px;
}

.prev {
  left: 10px;
}

.next {
  right: 10px;
}

.carousel-dots {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
}

.carousel-dots span {
  height: 10px;
  width: 10px;
  margin: 0 5px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  cursor: pointer;
}

.carousel-dots .active {
  background-color: #717171;
}
</style>

*items: []中为存在assets文件夹下的图片列表

2.在主 Vue 实例中,或者在任何其他组件中,可以使用刚刚创建的轮播图组件。

<script>
import Carousel from './components/Carousel.vue';

export default {
  components: {
    Carousel
  }
};
</script>

<style>
#app {
  text-align: center;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

组件通过 data 管理当前显示的图片索引(currentIndex),并包含前一张、下一张的切换方法(prev 和 next),以及根据用户点击的指示点跳转到特定图片的方法(goToIndex)。
carousel-inner 使用 CSS transform 属性来移动图片的视图,实现轮播效果。箭头按钮和指示点样式也被定义。
在 mounted 生命周期钩子中启动自动播放,并在 beforeDestroy 钩子中停止它。
效果:

posted @ 2024-08-13 10:53  zi_ziju  阅读(616)  评论(0)    收藏  举报