欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue项目中使用swiper

程序员文章站 2022-04-12 11:57:40
...

首先从引入开始
下载依赖 npm i swiper -S

 <div class="swiper-container homeSwiper" ref="homeSwiper">
    <div class="swiper-wrapper">
       <div class="swiper-slide" v-for="banner in banners" :key="banner.id">
          <img :src="banner.imgUrl" alt />
       </div>
    </div>
          <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>
     <!-- 如果需要导航按钮 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
 </div>
// 引入swiper的文件
import Swiper from "swiper/swiper-bundle.min.js";
import { mapState } from "vuex";
export default {
  name: "ListContainer",
  computed: {
    ...mapState({
      banners: (state) => state.home.banners,
    }),
  },
  watch: {
    banners: {
      deep: true,
      // banners有变化才会触发
      handler(val) {
        console.log(val);
        if (val.length <= 0 || val === undefined) return;
        // 1.$refs.homeSwiper 避免多个组件渲染重复
        // 2.mounted时只是将vue渲染完成的页面刚刚挂载到DOM树上, 可是离样式等渲染完成还有一段时间
        // 3.等轮播图数据放到data或vuex仓库中, 再注册$nextTick
        this.$nextTick(() => {
          new Swiper(this.$refs.homeSwiper, {
            effect: "fade",
            autoplay: true, // 自动播放
            direction: "horizontal", // 垂直切换选项
            loop: true, // 循环模式选项
            // 如果需要分页器
            pagination: {
              el: ".swiper-pagination",
            },
            // 如果需要前进后退按钮
            navigation: {
              nextEl: ".swiper-button-next",
              prevEl: ".swiper-button-prev",
            },
            // 如果需要滚动条
            scrollbar: {
              el: ".swiper-scrollbar",
            },
          });
        });
      },
    },
  },
}