在 Vue3 中使用 Swiper 实现滑动、点击按钮切换轮播图

2,110 阅读1分钟

Swiper 官网

Swiper Vue.js Components

Vue2 和 Vue3 的使用方式相同。

现有的 UI 框架基本上都不能实现滑动切换轮播图,只能点击按钮切换。故使用 Swiper 实现业务需求,踩了很多坑,总结出了下面的一个 demo。

安装

npm i swiper

使用

Vue3 demo

<script setup lang="ts">
import { ref } from 'vue'
import { Swiper, SwiperSlide } from 'swiper/vue'
import type { Swiper as SwiperClass } from 'swiper/types'
import 'swiper/css'

const swiperRef = ref<SwiperClass>()

function onSwiper(swiper: SwiperClass) {
	swiperRef.value = swiper
}
</script>

<template>
	<button @click="swiperRef && swiperRef.slidePrev()">prev</button>
	<button @click="swiperRef && swiperRef.slideNext()">next</button>
	<swiper :slides-per-view="1" @swiper="onSwiper">
		<swiper-slide>Slide 1</swiper-slide>
		<swiper-slide>Slide 2</swiper-slide>
		<swiper-slide>Slide 3</swiper-slide>
	</swiper>
</template>

<style lang="less" scoped>
.swiper {
	height: 200px;
}
</style>

如何通过点击按钮切换轮播图?

使用 Swiper 实例的 slidePrev 和 slideNext 方法。

swiper 事件是 Vue 和 React 这些框架的额外事件,用于获取 Swiper 实例,具体实现代码见上方 demo。

关于 useSwiper

Swiper Vue provides useSwiper hook to easliy get the Swiper instance in components inside of Swiper:

<template>
  <button @click="swiper.slideNext()">Slide to the next slide</button>
</template>
<script>
  import { useSwiper } from 'swiper/vue';

  export default {
    setup() {
      const swiper = useSwiper();

      return {
        swiper,
      };
    },
  };
</script>

上面是摘抄自官网的一段描述。useSwiper 也是用于获取 Swiper 实例,但是在实际使用中会报错,如果不知道如何解决,推荐使用 swiper 事件。

去 GitHub 上逛了一圈 Issues,说是要在 Swiper 组件内部调用 useSwiper,感兴趣的可以试试。

20240115154342.png

20240115154518.png