关于我在vue3中使用swiper的使用碰到swiper-slide的width特别大的这件事儿

一. 环境

  "vue": "^3.3.8",
  "swiper": "^10.0.4",

二. 问题描述

原代码:

<template>
	<swiper
		class="wq-swiper"
		:space-betwee="spaceBetween"
		:pagination="{ clickable: true }"
		:modules="modules"
		@swiper="onSwiper"
		@slide-change="onSlideChange"
	>
		<swiper-slide>
			<div class="mh2" style="font-size: 36px; height: 100px; background: #96ccff; color: blue">hello-world</div>
		</swiper-slide>
		<swiper-slide>
			<div class="mh2" style="font-size: 36px; height: 100px; background: #96ccff; color: blue">hello-卡开心</div>
		</swiper-slide>
	</swiper>
</template>
<script setup lang="ts">

import { Swiper, SwiperSlide } from 'swiper/vue';
import { Navigation, Pagination, Scrollbar, A11y } from 'swiper/modules';

import { WqSwiperItem } from '@/components/WqSwiper/type';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';

type Props = {
	spaceBetween?: number;
	loop?: boolean;
	swiperItems: WqSwiperItem[];

	onSwiper?: (swiper: any) => void;
	onSlideChange?: (swiper: any) => void;
};

const props = withDefaults(defineProps<Props>(), {
	slidesPerView: 'auto',
	spaceBetween: 10,
	loop: false,
});

const modules = [Navigation, Pagination, Scrollbar, A11y];

</script>

在这里插入图片描述
发现这里的width非常大, 奇怪的是我没有设置任何的行内样式啊

三. 问题的解决

	<swiper
		class="wq-swiper"
		slides-pre-view="auto"
		:space-betwee="spaceBetween"
		:pagination="{ clickable: true }"
		:modules="modules"
		@swiper="onSwiper"
		@slide-change="onSlideChange"
	> ... </swiper>

在这里需要添加上slides-pre-view="auto" 或者 :slides-pre-view="n" n> = 2)
n = 1时需要为swiper 添加 width属性

四. 原因

swiper大小可变, 内部的slides的width是根据swiper的大小进行计算的,因为内部的slide自己在写样式的时候设置为100%在加上其他的一些样式会将swiper撑开,swiper大小变化后影响后面slide的width的计算.

所以在使用swiper的时候除了注意loopslides-pre-views`的一起使用还要注意swiper可变的情况,要么对slide大小进行控制,要么对swiper进行控制, 可以使用max-width属性对最大宽度进行限制

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值