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中实现定时器功能是一个常见需求,尤其是在需要周期性执行任务的场景下,本文给大家介绍了基于asyncio和threading模块,可扩展的异步定... 目录需求背景代码1. 单例事件循环的实现2. 事件循环的运行与关闭3. 定时器核心逻辑4. 启动与停

基于Python实现读取嵌套压缩包下文件的方法

《基于Python实现读取嵌套压缩包下文件的方法》工作中遇到的问题,需要用Python实现嵌套压缩包下文件读取,本文给大家介绍了详细的解决方法,并有相关的代码示例供大家参考,需要的朋友可以参考下... 目录思路完整代码代码优化思路打开外层zip压缩包并遍历文件:使用with zipfile.ZipFil

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

C#实现将Excel表格转换为图片(JPG/ PNG)

《C#实现将Excel表格转换为图片(JPG/PNG)》Excel表格可能会因为不同设备或字体缺失等问题,导致格式错乱或数据显示异常,转换为图片后,能确保数据的排版等保持一致,下面我们看看如何使用C... 目录通过C# 转换Excel工作表到图片通过C# 转换指定单元格区域到图片知识扩展C# 将 Excel

Java Optional的使用技巧与最佳实践

《JavaOptional的使用技巧与最佳实践》在Java中,Optional是用于优雅处理null的容器类,其核心目标是显式提醒开发者处理空值场景,避免NullPointerExce... 目录一、Optional 的核心用途二、使用技巧与最佳实践三、常见误区与反模式四、替代方案与扩展五、总结在 Java

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n

基于Java实现回调监听工具类

《基于Java实现回调监听工具类》这篇文章主要为大家详细介绍了如何基于Java实现一个回调监听工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录监听接口类 Listenable实际用法打印结果首先,会用到 函数式接口 Consumer, 通过这个可以解耦回调方法,下面先写一个

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Qt中QGroupBox控件的实现

《Qt中QGroupBox控件的实现》QGroupBox是Qt框架中一个非常有用的控件,它主要用于组织和管理一组相关的控件,本文主要介绍了Qt中QGroupBox控件的实现,具有一定的参考价值,感兴趣... 目录引言一、基本属性二、常用方法2.1 构造函数 2.2 设置标题2.3 设置复选框模式2.4 是否

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指