使用swiper实现无限滚动

发布于:2024-05-18 ⋅ 阅读:(211) ⋅ 点赞:(0)

首先因为swiper 版本较多,这里使用的是5.4.5版本。(使用 vue3-seamless-scroll 插件也是可以实现的,详细见vue3SeamlessScroll 实现简单列表无限循环滚动

1. 安装

npm install swiper@5

2. 全局引入样式

// main.ts
import "swiper/css/swiper.css"; // 引入样式文件 注意5和6版本的样式文件不一致

3.示例代码

<template>
    <div class="swiper-container">
      <div class="swiper-wrapper">
        <div class="swiper-slide" v-for="slide in slides" :key="slide">
            <div class="slide-box">Slide {{ slide }}</div>
        </div>
      </div>
      <!-- 如果需要分页器 -->
      <!-- <div class="swiper-pagination"></div> -->
      
      <!-- 如果需要导航按钮 -->
      <!-- <div class="swiper-button-prev"></div>
      <div class="swiper-button-next"></div> -->
   
      <!-- 如果需要滚动条 -->
      <!-- <div class="swiper-scrollbar"></div> -->
    </div>
  </template>
   
<script setup>
import { ref, onMounted } from 'vue';
import Swiper from 'swiper';
const slides = ref([1, 2, 3, 4, 5,6,7,8,9,10]);
let mySwiper = null
onMounted(() => {
    mySwiper = new Swiper('.swiper-container', {
        // 配置选项
        direction: 'vertical',
        loop: true,
        slidesPerView: 3, // 每页显示几个slide
        speed: 800, // 速度
        mousewheel: true, // 鼠标滚轮控制
        autoplay:{
            delay: 1000, // 自动播放的间隔时间
            disableOnInteraction: false, // 用户操作后是否停止自动播放
        },
        // observer: true, //修改swiper自己或子元素时,自动初始化swiper
        // observeParents: false, //修改swiper的父元素时,自动初始化swiper
        // 如果需要分页器
        pagination: {
            el: '.swiper-pagination',
        },
        // 如果需要导航按钮
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        // 如果需要滚动条
        scrollbar: {
            el: '.swiper-scrollbar',
        },
    });
    const mySwiperElement = document.querySelector(".swiper-container")
    mySwiperElement.addEventListener("mouseenter",()=>{
        mySwiper.autoplay.stop();  // 鼠标移入时停止自动播放
    })
    mySwiperElement.addEventListener("mouseleave",()=>{
        mySwiper.autoplay.start();  // 鼠标移出时开始自动播放
    })
    // 监听鼠标滚轮事件
    mySwiperElement.addEventListener("wheel",(e)=>{
        // event.deltaY 正数表示向下滚动,负数表示向上滚动
        if(e.deltaY < 0){
            mySwiper.slidePrev();
        } else {
            mySwiper.slideNext();
        }
    },{ passive: true })
});
</script>
   
<style lang="scss" scoped>
    .swiper-container {
      width: 600px;
      height: 300px;
      background: url('../assets/bg.png') no-repeat;
      background-size: 100% auto;
    }
   
    .swiper-slide {
        background-position: center;
        background-size: cover;
        width: 100%;
        height: 100%;
        .slide-box{
            color: aliceblue;
            margin-bottom: 10px;
            height: calc(100% - 10px);
            border: 1px solid rgb(23, 81, 225);
            background-color: rgba(69, 132, 215, 0.3);
        }
    }
</style>

实现效果:

 


网站公告

今日签到

点亮在社区的每一天
去签到