Vue

Vue2中使用Swipe.js

2023-08-21  本文已影响0人  h2coder

依赖版本

添加依赖

npm i swiper@5.4.5

使用Swiper

<template>
    <!-- 轮播图 -->
    <div class="swiper">
      <div class="swiper-wrapper">
        <div
          class="swiper-slide"
          v-for="(item, index) in swiperList"
          :key="index"
        >
          <a href="javascript:;">
            <img :src="item" alt="" />
          </a>
        </div>
      </div>
      <!--分页器-->
      <div class="swiper-pagination"></div>
    </div>
</template>

<script>
export default {
  created() {
    this.getDetail();
  },
  data() {
    return {
      // 轮播图实例
      mySwiper: null,
      // 轮播图数据
      swiperList: [],
    };
  },
  methods: {
    // 初始化轮播图组件
    initSwper() {
      // swiper初始化
      this.mySwiper = new Swiper(".swiper", {
        speed: 1000,
        loop: true,
        autoplay: {
          disableOnInteraction: false,
          delay: 2000,
        },
        pagination: {
          el: ".swiper-pagination",
          bulletClass: "swiper-indicator",
          bulletActiveClass: "swiper-indicator-active",
        },
        centeredSlides: true,
        //修改swiper自己或子元素时,自动初始化swiper
        observer: true,
        //修改swiper的父元素时,自动初始化swiper
        observeParents: true,
        observerUpdate: true,
      });
    },
    // 获取详情数据
    async getDetail() {
      // 获取传递过来的房源Id
      const id = this.$route.params.id;
      //发送请求,获取房源详情
      const result = await axios({
        url: `http://localhost:8080/houses/${id}`,
        method: "GET",
      });
      // 构建轮播图数据
      this.swiperList = this.detail.houseImg.map((item) => {
        return `http://localhost:8080${item}`;
      });
    },
  },
  watch: {
    // 监听轮播图列表数据
    swiperList: {
      // 深度监听
      deep: true,
      handler() {
        // DOM更新完毕后,更新轮播图
        this.$nextTick(() => {
          this.initSwper();
        });
      },
    },
  },
};
</script>

<!-- 轮播图的样式,注意不能加scoped,否则Vue会增加一个唯一Id的选择器来修改样式,导致Swipe找不到样式 -->
<style lang="css">
/* 轮播图指示器-未选中样式 */
.swiper-indicator {
  position: relative;
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 100%;
  background: black;
  opacity: 0.5;
  margin: 0 4px;
}

/* 轮播图指示器-高亮,会继承上面基础样式 */
.swiper-indicator-active {
  background: #21b97a;
  opacity: 1;
}
</style>

<style lang="less" scoped>
// 轮播图
.swiper {
    height: 68.267vw;

    img {
        font-weight: 100%;
        height: 100%;
    }
}
</style>
上一篇下一篇

猜你喜欢

热点阅读