Vue3+elementplus实现图片上传下载(最强实践)

本文主要是介绍Vue3+elementplus实现图片上传下载(最强实践),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 图片上传子组件:

实现照片的上传,预览,以及转成以逗号隔开的图片地址,即时监听,并发送消息到父组件。

<!-- ImageUploader.vue -->  
<template><div><el-upload class="avatar-uploader" :http-request="customUpload" :before-upload="beforeUpload":show-file-list="false" multiple><el-icon><Plus style="background-color: azure;" /></el-icon></el-upload><div v-for="(image, index) in imageUrls" :key="index"><el-image :src="image" style="width: 100px; height: 100px" fit="cover" :preview-src-list="[image]"><template #placeholder><div class="image-slot">Loading<span class="dot">...</span></div></template></el-image><el-button @click="deleteImage(image)" el-icon=""><el-icon><DeleteFilled /></el-icon></el-button></div></div>
</template>  <script setup lang="ts" name="ImageUploader">
import { computed, ref, watch } from 'vue';
import { upload } from '@/api/file'
import { ElMessage } from 'element-plus'
import emitter from '@/utils/emitter'// 上传文件,请求接口,并且将结果存储
function customUpload(file: any) {let formData = new FormData();formData.append('file', file.file)upload(formData).then((response: any) => {const imgUrl = response.data;imageUrls.value.push(imgUrl);})
}// 图片url
const imageUrls = ref([]);// 计算属性,用于生成逗号隔开的图片地址字符串  
const commaSeparatedUrls = computed(() => imageUrls.value.join(','));
// 监听图片地址变化,即时发送最新数据给父组件
watch(imageUrls, () => {console.log('发送图片地址', commaSeparatedUrls.value)emitter.emit('send-imageUrls', commaSeparatedUrls.value)
}, { deep: true })// 图片校验规则
const beforeUpload = (file: any) => {const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';const isLt2M = file.size / 1024 / 1024 < 2;if (!isJPGOrPNG) {ElMessage.error('picture must be jpg/png format!')return false}if (!isLt2M) {ElMessage.error('picture size can not exceed 2MB!')return false}return true
};// 删除图片
const deleteImage = (imgUrl: any) => {// 从imageUrls数组中删除指定的图片URL  imageUrls.value.splice(imgUrl, 1);
};</script>  <style scoped> .avatar-uploader {color: skyblue;font-style: normal;}
</style>

表单父组件:

引入图片上传子组件,接受消息,并实现挂载之后取消绑定事件,避免占用内存 

<template><el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"class="demo-ruleForm" :size="formSize" status-icon><el-form-item label="类型"><el-radio-group v-model="ruleForm.type"><el-radio value="0">转租</el-radio><el-radio value="1">短租</el-radio><el-radio value="2">长租</el-radio><el-radio value="3">招租</el-radio></el-radio-group></el-form-item><el-form-item label="标题" prop="tittle"><el-input v-model="ruleForm.tittle" /></el-form-item><el-form-item label="地址" prop="address"><el-input v-model="ruleForm.address" /></el-form-item><el-form-item label="介绍" prop="content"><el-input v-model="ruleForm.content" /></el-form-item><el-form-item label="房间照片"><ImageUploader /></el-form-item><el-form-item><el-button type="primary" @click="submitForm(ruleFormRef)">Create</el-button><el-button @click="resetForm(ruleFormRef)">Reset</el-button></el-form-item></el-form>
</template><script lang="ts" setup>
import { reactive, ref, onUnmounted } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { type HouseInter } from '@/types/model';
import emitter from '@/utils/emitter'
import ImageUploader from '@/components/ImageUploader.vue'const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<HouseInter>({})const rules = reactive<FormRules<HouseInter>>({type: [{ required: true, message: '请选择房源类型', trigger: 'change' }],tittle: [{ required: true, message: '请填写标题', trigger: 'change' }],})// 接受图片上传子组件的图片地址最新消息
emitter.on('send-imageUrls', (value: string) => {ruleForm.housePhoto = valueconsole.log('接收图片地址', ruleForm.housePhoto)
})
onUnmounted(() => {// 组件卸载之后,解绑事件emitter.off('send-imageUrls')
})const submitForm = async (formEl: FormInstance | undefined) => {if (!formEl) returnawait formEl.validate((valid, fields) => {if (valid) {console.log('submit!')} else {console.log('error submit!', fields)}})
}const resetForm = (formEl: FormInstance | undefined) => {if (!formEl) returnformEl.resetFields()
}
</script><style scoped></style>

消息工具类

import mitt from 'mitt'
import { ref } from 'vue'let emitter = mitt()let num = ref(0)// 绑定事件
emitter.on('add', () => {console.log('add被调用了', num)
})
// 每隔1秒执行事件
setInterval(() => {// emitter.emit('add')
}, 1000)setTimeout(() => {// 解绑事件emitter.off('add')
}, 5000)export default emitter

这篇关于Vue3+elementplus实现图片上传下载(最强实践)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1147100

相关文章

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

虚拟机Centos7安装MySQL数据库实践

《虚拟机Centos7安装MySQL数据库实践》用户分享在虚拟机安装MySQL的全过程及常见问题解决方案,包括处理GPG密钥、修改密码策略、配置远程访问权限及防火墙设置,最终通过关闭防火墙和停止Net... 目录安装mysql数据库下载wget命令下载MySQL安装包安装MySQL安装MySQL服务安装完成

使用zip4j实现Java中的ZIP文件加密压缩的操作方法

《使用zip4j实现Java中的ZIP文件加密压缩的操作方法》本文介绍如何通过Maven集成zip4j1.3.2库创建带密码保护的ZIP文件,涵盖依赖配置、代码示例及加密原理,确保数据安全性,感兴趣的... 目录1. zip4j库介绍和版本1.1 zip4j库概述1.2 zip4j的版本演变1.3 zip4

SpringBoot整合(ES)ElasticSearch7.8实践

《SpringBoot整合(ES)ElasticSearch7.8实践》本文详细介绍了SpringBoot整合ElasticSearch7.8的教程,涵盖依赖添加、客户端初始化、索引创建与获取、批量插... 目录SpringBoot整合ElasticSearch7.8添加依赖初始化创建SpringBoot项

Zabbix在MySQL性能监控方面的运用及最佳实践记录

《Zabbix在MySQL性能监控方面的运用及最佳实践记录》Zabbix通过自定义脚本和内置模板监控MySQL核心指标(连接、查询、资源、复制),支持自动发现多实例及告警通知,结合可视化仪表盘,可有效... 目录一、核心监控指标及配置1. 关键监控指标示例2. 配置方法二、自动发现与多实例管理1. 实践步骤

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

MySQL 迁移至 Doris 最佳实践方案(最新整理)

《MySQL迁移至Doris最佳实践方案(最新整理)》本文将深入剖析三种经过实践验证的MySQL迁移至Doris的最佳方案,涵盖全量迁移、增量同步、混合迁移以及基于CDC(ChangeData... 目录一、China编程JDBC Catalog 联邦查询方案(适合跨库实时查询)1. 方案概述2. 环境要求3.

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命