Vue3 利用 Swiper 快速实现一个带有左右点击按钮可滑动的列表组件

预览

在这里插入图片描述

安装

pnpm add swiper
# or
npm install swiper

默认安装最新 swiper 版本,我这边是 ^11.1.3
注意:不需要安装什么 vue-awesome-swiper,就很莫名其妙多出来这么一个东西,我也是被网上那些千篇一律的方法给坑了

代码

这里选择直接封装成一个组件方便使用,话不多杯,直接上代码:

<script setup>
import { ref, reactive, defineExpose } from 'vue'

// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from 'swiper/vue'
// 引入 swiper 所需模块
import { Autoplay, Pagination, Navigation, Scrollbar A11y, Virtual } from 'swiper/modules'
// Import Swiper styles
import 'swiper/css'
import 'swiper/css/navigation'
import 'swiper/css/pagination'
import 'swiper/css/scrollbar'

// 在 modules 加入要使用的模块
const modules = reactive([Autoplay, Pagination, Navigation, Scrollbar, A11y, Virtual])

// 自定义的数据
const data = ref([1, 2, 3, 4, 5, 6, 7, 8])

let useSwiper = null
// 初始化 swiper
const onSwiper = (swiper) => {
    useSwiper = swiper
}

// 滑动事件
const onSliderChange = () => {
    console.log('slide change')
}

// 通过实例方法自定义上一个下一个事件
const prevEl = () => {
    useSwiper.slidePrev()
}
const nextEl = () => {
    useSwiper.slideNext()
}

// 暴露方法,用于父组件调用
defineExpose({
    prevEl,
    nextEl
})
</script>

<template>
    <swiper 
        :modules="modules"
        :slides-per-view="6"
        :space-between="10"
        :loop="true"
        :autoplay="{ delay: 4000, disableOnInteraction: false }"
        navigation
        :pagination="{ clickable: true }"
        :scrollbar="{ draggable: true }"
        @swiper="onSwiper"
        @sliderChange="onSliderChange"
    >
        <swiper-slide v-for="(item, index) in data" :key="index" :virtual-index="index">
            <div class="box">{{ item }}</div>
        </swiper-slide>
    </swiper>
</template>

<style scoped>
.box {
    width: 150px;
    height: 100px;
    background-color: lightblue;
}
</style>

说明

Swiper 组件 modules 属性包含额外需要引入的模块功能,如上述代码中引入了 Virtual 这个模块,表示虚拟列表,按需引入即可

下面是一些常用属性介绍:

  • slides-per-view:控制一次显示几张轮播图
  • space-between: 每张轮播图之间的距离,该属性不可以和 margin 属性同时使用
  • loop: 是否循环播放
  • autoplay: 是否自动轮播,delay 为间隔的毫秒数;disableOnInteraction 属性默认是 true,也就是当用户手动滑动后禁用自动播放
  • navigation:定义左右切换箭头
  • pagination:控制是否可以点击圆点指示器切换轮播
  • scrollbar:是否显示轮播图的滚动条,draggable 设置为 true 就可以拖动底部的滚动条

更多操作请移步 Swiper 官网

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值