Vue3使用触摸滑动插件(Swiper)
Vue2使用触摸滑动插件Swiper参考文档Swiper官方Swiper APISwiper VueSwiper Demos本文使用版本Swiper12.0.3安装插件pnpm add swiper本文基于Swiper插件进行封装主要实现两种形式的轮播图展示首页轮播图切换展示type: banner走马灯轮播图滚动展示type: carousel信息展播模式type: broadcast可自定义设置以下属性轮播图片数组images类型Image[]默认 []轮播区域宽度width类型number | string单位 px默认 100%轮播区域高度height类型number | string单位 px默认 100%滑动轮播模式mode类型banner | carousel | broadcast默认 bannerbanner轮播图模式carousel走马灯模式broadcast信息展播模式是否显示导航navigation类型boolean默认 false切换动画效果effect类型slide | fade | cube | flip | coverflow | cards | creative默认 slide自动切换的时间间隔delay仅当 modebanner 时生效单位 ms类型number默认 3000切换过渡的动画持续时间speed单位 ms类型number默认 300是否循环切换loop类型boolean默认 true当鼠标移入走马灯时是否暂停自动轮播pauseOnMouseEnter仅当 mode: banner 或 mode: carousel 时生效类型boolean默认 false是否可以鼠标拖动swipe类型boolean默认 true预加载时的 loading 颜色preloaderColor类型theme | white | black默认 theme效果如下图在线预览①创建触摸滑动组件Swiper.vue其中引入使用了以下工具函数获取依赖注入 useInjectscript setup langts import { ref, computed } from vue import { useInject } from components/utils import type { Swiper as SwiperTypes } from swiper/types import { Swiper, SwiperSlide } from swiper/vue import { Navigation, Pagination, Autoplay, Mousewheel, EffectFade, EffectCube, EffectFlip, EffectCoverflow, EffectCards, EffectCreative } from swiper/modules import swiper/css import swiper/css/navigation import swiper/css/pagination // import swiper/css/autoplay // 目标文件为空 // import swiper/css/mousewheel // 目标文件为空 import swiper/css/effect-fade import swiper/css/effect-cube import swiper/css/effect-flip // import swiper/css/effect-coverflow // 目标文件为空 import swiper/css/effect-cards import swiper/css/effect-creative export interface Image { name?: string // 图片名称 src: string // 图片地址 link?: string // 图片跳转链接 target?: _self | _blank // 如何打开跳转链接 } export interface Props { images?: Image[] // 轮播图片数组 width?: number | string // 轮播区域宽度单位 px height?: number | string // 轮播区域高度单位 px mode?: banner | carousel | broadcast // banner: 轮播图模式; carousel: 走马灯模式; broadcast: 信息展播模式 navigation?: boolean // 是否显示导航 effect?: slide | fade | cube | flip | coverflow | cards | creative // 切换动画效果 delay?: number // 自动切换的时间间隔仅当 mode: banner 时生效单位 ms speed?: number // 切换过渡的动画持续时间单位 ms loop?: boolean // 是否循环切换 pauseOnMouseEnter?: boolean // 当鼠标移入走马灯时是否暂停自动轮播仅当 mode: banner 或 mode: carousel 时生效 swipe?: boolean // 是否可以鼠标拖动 preloaderColor?: theme | white | black // 预加载时的 loading 颜色 } const props withDefaults(definePropsProps(), { images: () [], width: 100%, height: 100%, mode: banner, navigation: false, effect: slide, delay: 3000, speed: 300, loop: true, pauseOnMouseEnter: false, swipe: true, preloaderColor: theme }) const autoplayBanner ref({ delay: props.delay, disableOnInteraction: false, // 用户操作 swiper 之后是否禁止 autoplay。默认为 true停止。 pauseOnMouseEnter: props.pauseOnMouseEnter // 鼠标置于 swiper 时暂停自动切换鼠标离开时恢复自动切换默认 false }) const modulesCarousel ref([Autoplay]) const autoplayCarousel refobject | boolean({ delay: 0, disableOnInteraction: false }) const modulesBroadcast ref([Navigation, Pagination, Mousewheel]) const { colorPalettes } useInject(Swiper) // 主题色注入 const emits defineEmits([swiper, change]) const swiperWidth computed(() { if (typeof props.width number) { return ${props.width}px } else { return props.width } }) const swiperHeight computed(() { if (typeof props.height number) { return ${props.height}px } else { return props.height } }) const modulesBanner computed(() { const modules [Navigation, Pagination, Autoplay] const effectMoudles { fade: EffectFade, cube: EffectCube, flip: EffectFlip, coverflow: EffectCoverflow, cards: EffectCards, creative: EffectCreative } if (props.effect ! slide) { modules.push(effectMoudles[props.effect]) } return modules }) function onSwiper(swiper: SwiperTypes) { emits(swiper, swiper) if (props.mode carousel props.pauseOnMouseEnter) { swiper.el.onmouseenter () { // 移入暂停 swiper.autoplay.stop() } swiper.el.onmouseleave () { // 移出启动 swiper.autoplay.start() } } } function onSlideChange(swiper: SwiperTypes) { emits(change, swiper) } function getImageName(image: Image) { // 从图片地址 src 中获取图片名称 if (image.name) { return image.name } else { const res image.src.split(?)[0].split(/) return res[res.length - 1] } } /script template Swiper v-ifmode banner classswiper-banner :class{ swiper-no-swiping: !swipe } :style --swiper-width: ${swiperWidth}; --swiper-height: ${swiperHeight}; --swiper-primary-color: ${colorPalettes[5]}; --swiper-timing-function: cubic-bezier(0.65, 0, 0.35, 1); :modulesmodulesBanner :navigationnavigation :slides-per-view1 :autoplayautoplayBanner :effecteffect :speedspeed :looploop lazy swiperonSwiper slideChangeonSlideChange v-bind$attrs SwiperSlide v-for(image, index) in images :keyindex component :isimage.link ? a : div classswiper-link :hrefimage.link :targetimage.target ? image.target : _blank img classswiper-image :srcimage.src :altgetImageName(image) loadinglazy / /component div :classswiper-lazy-preloader swiper-lazy-preloader-${preloaderColor}/div /SwiperSlide /Swiper Swiper v-ifmode carousel classswiper-carousel swiper-no-swiping :style --swiper-width: ${swiperWidth}; --swiper-height: ${swiperHeight}; --swiper-primary-color: ${colorPalettes[5]}; --swiper-timing-function: linear; :modulesmodulesCarousel :autoplayautoplayCarousel :speedspeed :looploop lazy swiperonSwiper slideChangeonSlideChange v-bind$attrs SwiperSlide v-for(image, index) in images :keyindex component :isimage.link ? a : div classswiper-link :hrefimage.link :targetimage.target ? image.target : _blank img classswiper-image :srcimage.src :altgetImageName(image) loadinglazy / /component div :classswiper-lazy-preloader swiper-lazy-preloader-${preloaderColor}/div /SwiperSlide /Swiper Swiper v-ifmode broadcast classswiper-broadcast :style --swiper-width: ${swiperWidth}; --swiper-height: ${swiperHeight}; --swiper-primary-color: ${colorPalettes[5]}; --swiper-timing-function: cubic-bezier(0.65, 0, 0.35, 1); :modulesmodulesBroadcast :navigationnavigation :speedspeed :looploop lazy swiperonSwiper slideChangeonSlideChange v-bind$attrs SwiperSlide v-for(image, index) in images :keyindex component :isimage.link ? a : div classswiper-link :hrefimage.link :targetimage.target ? image.target : _blank img classswiper-image :srcimage.src :altgetImageName(image) loadinglazy / /component div :classswiper-lazy-preloader swiper-lazy-preloader-${preloaderColor}/div /SwiperSlide /Swiper /template style langless scoped .swiper-banner { width: var(--swiper-width); height: var(--swiper-height); :deep(.swiper-wrapper) { transition-timing-function: var(--swiper-timing-function); } } .swiper-carousel { width: var(--swiper-width); height: var(--swiper-height); :deep(.swiper-wrapper) { // 自动切换过渡效果设置 transition-timing-function: var(--swiper-timing-function); // 线性过渡模拟走马灯效果 } } .swiper-broadcast { width: var(--swiper-width); height: var(--swiper-height); :deep(.swiper-wrapper) { transition-timing-function: var(--swiper-timing-function); } } .swiper-link { display: block; height: 100%; .swiper-image { width: 100%; height: 100%; object-fit: cover; cursor: pointer; } } .swiper { --swiper-theme-color: var(--swiper-primary-color); } :deep(.swiper-pagination-bullet) { width: 12px; height: 12px; } .swiper-lazy-preloader-theme { --swiper-preloader-color: var(--swiper-primary-color); } /style②在要使用的页面引入其中引入使用了以下组件Vue3间距SpaceVue3弹性布局FlexVue3徽标BadgeVue3按钮Buttonscript setup langts import Swiper from ./Swiper.vue import { ref, shallowReactive, onBeforeMount } from vue import pkg from /package.json import type { SwiperImage } from vue-amazing-ui const images refSwiperImage[]([]) function loadImages() { for (let i 1; i 6; i) { images.value.push({ name: image-${i}, src: https://cdn.jsdelivr.net/gh/themusecatcher/resources0.1.2/${i}.jpg, link: https://cdn.jsdelivr.net/gh/themusecatcher/resources0.1.2/${i}.jpg }) } } onBeforeMount(() { // 组件已完成响应式状态设置但未创建DOM节点 loadImages() }) function onChange(swiper: any) { console.log(slider change, swiper) } const effects [slide, fade, cube, flip, coverflow, cards] const creativeEffects [ { prev: { shadow: true, translate: [0, 0, -400] }, next: { translate: [100%, 0, 0] } }, { prev: { shadow: true, translate: [-120%, 0, -500] }, next: { shadow: true, translate: [120%, 0, -500] } }, { prev: { shadow: true, translate: [-20%, 0, -1] }, next: { translate: [100%, 0, 0] } }, { prev: { shadow: true, translate: [0, 0, -800], rotate: [180, 0, 0] }, next: { shadow: true, translate: [0, 0, -800], rotate: [-180, 0, 0] } }, { prev: { shadow: true, translate: [-125%, 0, -800], rotate: [0, 0, -90] }, next: { shadow: true, translate: [125%, 0, -800], rotate: [0, 0, 90] } }, { prev: { shadow: true, origin: left center, translate: [-5%, 0, -200], rotate: [0, 100, 0] }, next: { origin: right center, translate: [5%, 0, -200], rotate: [0, -100, 0] } } ] const navigation shallowReactive{ [key: string]: any }({}) function onBroadcastSwiper(swiper: any) { console.log(carousel, swiper) navigation.prevEl swiper.navigation.prevEl navigation.prevEl.style.display none navigation.nextEl swiper.navigation.nextEl navigation.nextEl.style.display none } function onPrev() { navigation.prevEl.click() } function onNext() { navigation.nextEl.click() } /script template div h1Swiper 参考文档/h1 ul classm-list li a classu-file hrefhttps://swiperjs.com/ target_blankSwiper官方/a /li li a classu-file hrefhttps://swiperjs.com/swiper-api target_blankSwiper API/a /li li a classu-file hrefhttps://swiperjs.com/vue target_blankSwiper Vue/a /li li a classu-file hrefhttps://swiperjs.com/demos target_blankSwiper Demos/a /li /ul Space classmt30 gapsmall h1swiper/h1 Tag colorvolcano{{ pkg.dependencies.swiper }}/Tag /Space h2 classmt30 mb10基本使用/h2 Swiper :imagesimages :height640 :speed800 :pagination{ dynamicBullets: true, clickable: true } changeonChange / h2 classmt30 mb10各种切换动画/h2 Flex :gap48 wrapwrap Badge stylewidth: 30% :valueeffect colorvolcano v-for(effect, index) in effects :keyindex Swiper styledisplay: inline-block :imagesimages :height240 :speed600 :pagination{ dynamicBullets: true, clickable: true } :effecteffect / /Badge /Flex h2 classmt30 mb10自定义切换动画/h2 Flex :gap48 wrapwrap Badge stylewidth: 30% valuecreative colorcyan v-for(creativeEffect, index) in creativeEffects :keyindex Swiper styledisplay: inline-block :imagesimages :height240 :speed600 :pagination{ dynamicBullets: true, clickable: true } effectcreative :creativeEffectcreativeEffect / /Badge /Flex h2 classmt30 mb10走马灯/h2 Swiper :imagesimages modecarousel :height240 :slides-per-view3 :space-between20 :speed2500 / h2 classmt30 mb10信息展播/h2 Flex vertical gapmiddle Space Button typeprimary clickonPrevPrev/Button Button typeprimary clickonNextNext/Button /Space Swiper :imagesimages modebroadcast :height280 :speed600 :pagination{ dynamicBullets: true, clickable: true } :slides-per-view3 :space-between30 navigation mousewheel swiperonBroadcastSwiper / /Flex /div /template