Vue 实现轮播图

<template>
  <div class="carousel">
    <div class="main" ref="main">
      
      <div class="banner">
        <a href="javascript:" v-for=" (item, index) in images" :key="index">
          
          <div
            class="banner-slide"
            :style="{ backgroundImage: `url(${item})`}"
            @mouseover="mouseOver()"
            @mouseout="mouseOut(index)"
            ref="slide_img"
          >div>
        a>
      div>
      
      <a href="javascript:void(0)" class="button prev" ref="prev" @click="toPrev">a>
      <a href="javascript:void(0)" class="button next" ref="next" @click="toNext">a>
      <div class="dots">
        <span
          v-for=" (item, index) in dots"
          :key="index"
          @click="dotsChecked(index)"
          ref="dots"
          :class="index === 0 ? { dots_active } : '' "
        >span>
      div>
    div>
  div>
template>
<script>
export default {
  name: "carousel",
  data() {
    return {
      index: 0,
      timer: null,
      images: [
        "https://i1.mifile.cn/a4/xmad_1562317906034_yYDfN.jpg",
        "https://i1.mifile.cn/a4/xmad_15625789613185_yOkET.jpg",
        "https://i1.mifile.cn/a4/xmad_15623260229891_iSOkA.jpg"
      ],
      dots: [0, 1, 2],
      dots_active: true
    };
  },
  created() {
    this.mouseOut(this.index);
  },
  methods: {
    changeImg(index) {
      for (let i = 0; i < this.images.length; i++) {
        this.$refs.slide_img[i].style.display = "none";
        this.$refs.dots[i].className = " ";
      }

      this.$refs.slide_img[index].style.display = "block";
      this.$refs.dots[index].className = "dots_active";
    },
    mouseOver() {
      if (this.timer) clearInterval(this.timer);
    },
    mouseOut(index) {
      let that = this;
      this.timer = setInterval(function() {
        index++;
        if (index >= that.images.length) {
          index = 0;
        }
        that.index = index;
        that.changeImg(index);
      }, 2000);
    },
    toPrev() {
      this.index--;
      if (this.index < 0) this.index = this.images.length - 1;
      this.changeImg(this.index);
    },
    toNext() {
      this.index++;
      if (this.index >= this.images.length) this.index = 0;
      this.changeImg(this.index);
    },
    dotsChecked(index) {
      for (let i = 0; i < this.images.length; i++) {
        this.$refs.dots[i].className = " ";
      }
      this.changeImg(index);
    }
  }
};

</script>



你可能感兴趣的:(Vue学习笔记)