Vueはシンプルなカルーセルコンポーネントを実装しています

Vueはシンプルなカルーセルコンポーネントを実装しています

コンポーネントHTMLコード

  <div class="banner">
    <div
      class="swiperList"
      v-for="(item, index) in imgUrl"
      :key="index"
      v-show="currentindex == index"
    >
      <a href="">
        <img :src="item.src" alt="" />
      </a>
    </div>
    <div class="dots">
      <span
        class="dot"
        v-for="(item, index) in imgUrl"
        :key="index"
        @click="dotClick(index)"
        :class="index == currentindex ? 'active' : ''"
      ></span>
    </div>
  </div>
</template>

機能コード

<script>
// import banner from "../../assets/img/banner/banner-A.jpg"
export default {
  name: "BannerSwiper",
  data() {
    return {
      currentindex: 0,
      imgUrl: [
        { src: require("../../assets/img/banner/banner-A.jpg") },
        { src: require("../../assets/img/banner/banner-B.jpg") },
        { src: require("../../assets/img/banner/banner-C.jpg") },
        { src: require("../../assets/img/banner/banner-D.jpg") },
        { src: require("../../assets/img/banner/banner-E.jpg") }
      ]
    };
  },
  created() {
    this.play();
  },
  methods: {
    play() {
      //用定时器控制每张图的显示时间
      this.timer = setInterval(this.autoPlay, 3000);
    },
    autoPlay() {
      this.currentindex++;
      if (this.imgUrl.length == this.currentindex) {
        this.currentindex = 0;
      }
    },
    dotClick(index) {
      this.currentindex = index;
    }
  },
  beforeUnmount() {
    clearInterval(this.timer); //清除定时器
  }
};
</script>

スタイル

<style lang="less" scoped>
.banner {
  position: relative;
}
.swiperList {
  z-index: 10;
  a {
    img {
      width: 100%;
    }
  }
}
.dots {
  display: flex;
  justify-content: center;
  margin-top: -20px;
  height: 20px;
  line-height: 20px;
  z-index: 11;
  .dot {
    width: 10px;
    height: 10px;
    background: #ffffff;
    border-radius: 50%;
    margin-left: 10px;
  }
  .active {
    background: #cf0000;
  }
}
</style>

おすすめ

転載: blog.csdn.net/weixin_45498515/article/details/111809015