使用 Vue3 + TypeScript 实现图片预览组件

简介

在现代的 Web 应用中,图片预览是一个常见的需求。本文将介绍如何使用 Vue3 和 TypeScript 开发一个图片预览组件,支持展示单张或多张图片,并提供了丰富的配置选项。

组件功能

  • 支持单张或多张图片: 可以同时预览单张或多张图片,支持左右切换。
  • 自定义配置选项: 提供了丰富的配置选项,如图片缩放方式、懒加载、组件尺寸等。
  • 多张图片:无限循环预览,默认点击为首张,布局左右自适应父元素宽度,上下间距可通过参数(rowGap)控制。

组件实现

vue 复制代码
<script setup lang="ts" name="ImagePreview">
import { computed } from "vue";

interface ImageProps {
	imageUrl: string | string[]; // 图片地址 ==> 必传
	imageFit?: "fill" | "contain" | "cover" | "none" | "scale-down"; // 图片缩放方式 ==> 非必传(默认为 cover)
	imageLazy?: boolean; // 是否懒加载 ==> 非必传(默认为 true)
	height?: string; // 组件高度 ==> 非必传(默认为 150px)
	width?: string; // 组件宽度 ==> 非必传(默认为 150px)
	borderRadius?: string; // 组件边框圆角 ==> 非必传(默认为 8px)
	rowGap?: string; // 组件行间距 ==> 非必传(默认为 10px)
}
// 接收父组件参数并设置默认值
const props = withDefaults(defineProps<ImageProps>(), {
	imageUrl: "",
	imageFit: "cover",
	imageLazy: true,
	height: "150px",
	width: "150px",
	borderRadius: "8px",
	rowGap: "10px"
});

// 图片列表
const imageList = computed<string[]>(() => {
	if (Array.isArray(props.imageUrl)) {
		return props.imageUrl;
	}
	return [props.imageUrl];
});
</script>

<template>
	<div class="image-list">
		<div v-for="(item, index) in imageList" :key="index">
			<el-image
				class="image-style"
				:src="item"
				hide-on-click-modal
				:initial-index="index"
				:preview-src-list="imageList"
				:lazy="imageLazy"
				:fit="imageFit"
				:z-index="99999"
				preview-teleported
			/>
		</div>
	</div>
</template>

<style lang="scss" scoped>
.image-list {
	display: grid;
	grid-row-gap: v-bind(rowGap);
	grid-template-columns: repeat(auto-fill, v-bind(width));
	justify-content: space-between;
	.image-style {
		width: v-bind(width);
		height: v-bind(height);
		border-radius: v-bind(borderRadius);
	}
}
</style>

总结

通过使用 Vue3 和 TypeScript,我们可以轻松地开发出高度可定制的图片预览组件。这个组件可以帮助我们展示图片,提供了丰富的配置选项,以满足不同项目的需求。

希望本文能帮助你更好地理解如何开发图片预览组件!如果你有任何问题或建议,请随时提出。

相关推荐
be or not to be2 分钟前
前端基础实战笔记:文档流 + 盒子模型
前端·笔记
程序员码歌3 分钟前
短思考第264天,每天复盘5分钟,胜过你盲目努力1整年(2)
前端·后端·ai编程
nono牛3 分钟前
实战项目:设计一个智能温控服务
android·前端·网络·算法
敲敲了个代码7 小时前
从硬编码到 Schema 推断:前端表单开发的工程化转型
前端·javascript·vue.js·学习·面试·职场和发展·前端框架
张雨zy8 小时前
Pinia 与 TypeScript 完美搭配:Vue 应用状态管理新选择
vue.js·ubuntu·typescript
dly_blog9 小时前
Vue 响应式陷阱与解决方案(第19节)
前端·javascript·vue.js
消失的旧时光-19439 小时前
401 自动刷新 Token 的完整架构设计(Dio 实战版)
开发语言·前端·javascript
console.log('npc')9 小时前
Table,vue3在父组件调用子组件columns列的方法展示弹窗文件预览效果
前端·javascript·vue.js
用户47949283569159 小时前
React Hooks 的“天条”:为啥绝对不能写在 if 语句里?
前端·react.js
我命由我123459 小时前
SVG - SVG 引入(SVG 概述、SVG 基本使用、SVG 使用 CSS、SVG 使用 JavaScript、SVG 实例实操)
开发语言·前端·javascript·css·学习·ecmascript·学习方法