Swiper5的使用

2022/8/28 6:24:06

本文主要是介绍Swiper5的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Vue2中 Swiper5的使用

vue2 一般使用swiper5

安装

npm i swiper@5.0.1

在main.js中引入

import 'swiper/css/swiper.css'

在需要使用的组建里面引入

import Swiper from "swiper";

组件上template使用

//banner轮播
  <div class="swiper-container" id="mySwiper">
          <div class="swiper-wrapper">
            <div class="swiper-slide" v-for="carousel in getBannerList" :key="carousel.id">
              <img :src="carousel.imgUrl" />
            </div>
          </div>
          <!-- 如果需要分页器 -->
          <div class="swiper-pagination"></div>

          <!-- 如果需要导航按钮 -->
          <div class="swiper-button-prev"></div>
          <div class="swiper-button-next"></div>
  </div>

初始化Swiper

mounted或者watch的配置方法,用于初始化一个Swiper,返回初始化后的Swiper实例。两者都可以实现,看实际情况使用

mouted配置方法
//mouted配置方法
mounted() {
    var mySwiper = new Swiper(".swiper-container", {
      // direction: 'vertical', // 垂直切换选项
      loop: true, // 循环模式选项

      // 如果需要分页器
      pagination: {
        el: ".swiper-pagination",
      },

      // 如果需要前进后退按钮
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },

      // 如果需要滚动条
      /* scrollbar: {
            el: '.swiper-scrollbar',
        }, */
    });
  }

在mounted中直接初始化可能存在一些问题:dom还没有更新后就初始化了。
解决办法:settimeout,但不推荐。
可以在watch配置方法里面写

watch配置方法
  //watch
  watch: {
    list(监听对象): {
      // 立即监听,不管数据是否变化,立即执行一次,看情况使用
      immediate: true,
      deep:true,//深度监听,也是看情况使用
      handler(newValue, oldValue) {
        this.$nextTick(function () {
          // ".swiper-container"可以换成this.$refs.mySwiper
          var mySwiper = new Swiper(this.$refs.floor1Swiper, {
            // direction: 'vertical', // 垂直切换选项
            loop: true, // 循环模式选项

            // 如果需要分页器
            pagination: {
              el: ".swiper-pagination",
              clickable: true,
            },

            // 自动切换
            autoplay: true, //等同于以下设置

            // 如果需要前进后退按钮
            navigation: {
              nextEl: ".swiper-button-next",
              prevEl: ".swiper-button-prev",
            },

            // 如果需要滚动条
            // scrollbar: {
            //         el: '.swiper-scrollbar',
            //     },
          });
        });
      },
    },
  }


这篇关于Swiper5的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程