# Swiper

# 简介

Swiper 官网:https://www.swiper.com.cn (opens new window)
这个插件大家应该都很熟悉,官网也提供了完善的 api 文档和使用示例。 本项目中有两处使用了 swiper, 一处是首页的 banner,另一处是图片的预览。下面主要说下图片预览中的使用。

# 引入 Swiper

swiper 提供了适合 Vue 使用的 npm 包,但 7+ 版本的包在使用过程中,异步加载图片时第一张图始终无法加载出来(审查元素发现其 data-src 并未被替换为 src),最终我选择了常规的在 index.html 中引入 swiper.min.js 的方式进行处理。

# 使用

注意:Swiper7 使用的默认容器是 .swiper 与之前版本有差异。

<!-- class="swiper" 是 swiper 容器默认类名,不可删除 -->
<div class="swiper photo-swiper">
	<div class="swiper-wrapper">
		<div class="swiper-slide" v-for="item in photos" :key="item.id">
			<div class="slide-image">
				<!-- 图片懒加载,图片地址绑定在 data-src 上,并增加 `swiper-lazy` 类名 -->
				<img :data-src="item.url_larger" class="swiper-lazy" />

				<!-- 图片加载中动画 -->
				<div class="swiper-lazy-preloader">
						<m-spinner type="triple" color="#f60, #7fd901, #36a2e0" />
				</div>
			</div>
		</div>
	</div>
</div>
mounted() {
	this.$nextTick(() => {
		this.initSwiper();
	});
},

methods: {
	initSwiper() {
		// swiper实例中的 this 不是指向 Vue 的,所以需要在外面定义下
		let _this = this;

		// 实例化 swiper,该构造函数是在 `index.html` 中引入的,已在全局中,此处无需再次引入
		new Swiper(".photo-swiper", {
			lazy: true,
			initialSlide: this.initIndex,   // 默认展示图片的索引值
			observer: true,
			observeParents: true,
			watchSlidesVisibility: true,
			on: {
				slideChange: function () {
					// 此处的 this 指向的是当前 swiper 实例
					_this.initIndex = this.activeIndex;
				},
			},
		});
	}
}
上次更新: 6/24/2022, 6:15:24 PM
示例展示,因PC端无touch事件,请在手机上进行浏览