Vue实现简单轮播图

358 阅读1分钟

用Vue实现一个简单的轮播图 实现样式如下:

banner.png

HTML

<div class="banner">
      <div id="topBanner" style="padding-top: 5px" class="slide">
        <div
          v-for="(imgUrl, index) in bannerList"
          v-show="index === mark"
          :key="index"
          class="slideshow"
        >
          <a href="#">
            <img :src="imgUrl" style="width: 100%; height: 600px" />
          </a>
        </div>
        <div class="bar">
          <span
            v-for="(item, index) in bannerList"
            :class="{ active: index === mark }"
            :key="index"
          ></span>
        </div>
      </div>
    </div>

JS

export default {
  data() {
    return {
      msg: "index",
      bannerList: [
        "../src/assets/banner1.png",
        "../src/assets/enterMain.png",
        "../src/assets/helpBg.png",
      ],
      mark: 0, //比对图片索引的变量
    };
  },
   created() {
    this.play();
  },
  methods: {
    // 轮播图
    autoPlay() {
      console.log("执行了autoplay");

      this.mark++;
      if (this.mark === this.bannerList.length) {
        //当遍历到最后一张图片置零
        this.mark = 0;
      }
    },
    play() {
      setInterval(this.autoPlay, 2500);
    },
    change(i) {
      this.mark = i;
    },
  },
};

CSS

/* banner */

.banner {
  width: 100%;
  margin: 0 auto;
  position: relative;
}
.slide {
  width: 100%;
  height: 600px;
  margin: 0 auto;
  /* margin-top: 50px; */
  overflow: hidden;
  position: relative;
}

.slideshow {
  width: 100%;
  height: 600px;
}

.bar {
  position: absolute;
  width: 100%;
  bottom: 10px;
  margin: 0 auto;
  z-index: 10;
  text-align: center;
}
.bar span {
  width: 14px;
  height: 14px;
  background: #fff;
  display: inline-block;
  transform: rotate(45deg);
  margin-right: 20px;
}
.active {
  background: #a63300 !important;
}