vue3+vite+ts引入swiper并使用

  • Post author:
  • Post category:vue



安装swiper版本

npm install swiper@7.4.1
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/css";
import { Autoplay } from "swiper";

let modules = [Autoplay];
<swiper
      @swiper="onSwiper"
      :slidesPerView="3"
      :autoplay="{ delay: 2500, disableOnInteraction: true }"
      :loop="true"
      :direction="'vertical'"
      :space-between="10"
      :modules="modules"
      @mouseenter="enter"
      @mouseleave="leave"
    >
      <swiper-slide>Slide 1</swiper-slide>
      <swiper-slide>Slide 2</swiper-slide>
      <swiper-slide>Slide 3</swiper-slide>
      <swiper-slide>Slide 4</swiper-slide>
      <swiper-slide>Slide 5</swiper-slide>
      <swiper-slide>Slide 6</swiper-slide>
    </swiper>

因为我要实现的效果是竖行滚动,并且一页展示3条数据 所以 slidesPerView设置为3,direction设置为”‘vertical'” ,一定记住必须是双引号里面再包单引号,不然没效果。

自动播放的话,就要引入模块

import { Autoplay } from "swiper";

let modules = [Autoplay];,

咱也不知道为啥这样写,反正swiper7官方文档是喊这样写的。

然后如果想移入暂停就要先获取到swiper对象,但是获取到的是响应式对象,所以需要先转换为非响应式

//定义swiperNew,目的获取非响应式swiper
let swiperNew: any;

//鼠标移入
const enter = () => {
  swiperNew.autoplay.stop();
};
//鼠标移出
const leave=()=>{
  swiperNew.autoplay.start();
}
const onSwiper = (swiper: any) => {
  swiperNew = toRaw(swiper);  //拿到swiper对象再转换为非响应式
};

打印一下获取的对象

完事!!!!



版权声明:本文为qcg14774125原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。