vue3如何二次封装el-upload组件进行图片上传及删除

实现功能:
1、封装el-upload组件,父组件可以控制图片上传框的宽高
2、父组件可以传入提示信息,利用具名插槽
3、上传前的校验
4、实现删除功能

不同配置下的效果:
在这里插入图片描述
下边案例是图片上传的时候没有掉接口,在整体提交的时候才调用的接口,所以需要一个中间变量去接收他的图片回显
父组件引用:

<script setup lang="ts">
import {
   
    ref } from 'vue'
import {
   
    useUserStore } from '@/stores';
const userStore = useUserStore()
const img = ref(userStore.user.user_pic)
const selectRef = ref(null)
//1、调用el-upload中on-change事件
// const triggerChange = ()=>{
   
   
//   if(selectRef.value){
   
   
//     const file = new File ([""],"filename")
//     selectRef.value.onSelectFile(file,[])
//   }
// }

//2、点击按钮调用子组件,图片上传选择文件弹出框
const openFileDialog  =()=>{
   
   
  selectRef.value.$refs.uploadRef.$el.querySelector('input').click()
}
</script>

<template>
  <pageContainer title="更换头像">
     <uploadImg 
      v-model="img" ref="selectRef"
      width="200px" 
      height="200px" 
      line-height="200px"
    >
      <!-- 具名插槽 -->
      <template #tips>
      <div style="margin-top:10px;">
        <el-button type="primary" size="small" 
        @click="openFileDialog">更换头像</el-button>
        <el-button type="success" size="small" >上传头像</el-button>
      </
### Vue封装 Element UI 的 `el-upload` 组件Vue 项目中,通过封装 `el-upload` 组件可以提高代码的可重用性和维护性。以下是关于如何封装组件的一个完整示例。 #### 封装思路 为了使上传功能更加灵活和通用,在封装过程中需要考虑以下几个方面: - 支持自定义请求参数。 - 提供回调函数处理成功或失败的结果。 - 集成进度条显示以及错误提示等功能。 --- #### 实现步骤 ##### 1. 创建 Upload 组件 (UploadComponent.vue) ```vue <template> <div class="upload-component"> <!-- 使用 el-upload --> <el-upload :action="uploadUrl" :headers="headers" :on-success="handleSuccess" :on-error="handleError" :before-upload="beforeUpload" :show-file-list="false" multiple > <el-button type="primary">点击上传</el-button> </el-upload> <!-- 显示上传状态 --> <p v-if="statusMessage">{{ statusMessage }}</p> </div> </template> <script> export default { name: &#39;CustomUpload&#39;, props: { uploadUrl: { type: String, required: true, }, headers: { type: Object, default() { return {}; }, }, }, data() { return { statusMessage: &#39;&#39;, // 用于存储上传的状态消息 }; }, methods: { handleSuccess(response, file) { this.statusMessage = `文件 ${file.name} 上传成功`; this.$emit(&#39;success&#39;, response); }, handleError(err, file) { this.statusMessage = `文件 ${file.name} 上传失败:${err.message}`; this.$emit(&#39;error&#39;, err); }, beforeUpload(file) { const isLt2M = file.size / 1024 / 1024 < 2; // 文件大小限制为2MB if (!isLt2M) { this.statusMessage = &#39;上传文件大小不能超过 2MB!&#39;; return false; } return true; }, }, }; </script> <style scoped> .upload-component { margin-bottom: 20px; } </style> ``` --- ##### 2. 在父组件中使用封装好的 Upload 组件 假设我们有一个页面需要使用这个上传组件来完成图片或其他类型的文件上传操作: ```vue <template> <div> <h3>文件上传示例</h3> <custom-upload :upload-url="&#39;http://example.com/upload&#39;" :headers="{ Authorization: &#39;Bearer token&#39; }" @success="handleUploadSuccess" @error="handleUploadError" /> </div> </template> <script> import CustomUpload from &#39;./components/CustomUpload&#39;; export default { components: { CustomUpload }, methods: { handleUploadSuccess(response) { console.log(&#39;上传成功:&#39;, response); }, handleUploadError(error) { console.error(&#39;上传失败:&#39;, error); }, }, }; </script> ``` --- #### 关键点说明 1. **动态配置 URL 和 Headers** - `uploadUrl` 是上传的目标地址,可以通过属性传递给子组件[^1]。 - `headers` 可以用来设置额外的信息,比如认证令牌等。 2. **事件监听** -组件中的 `@success` 和 `@error` 事件允许父组件捕获并响应上传过程中的各种情况。 3. **校验逻辑** - 在 `beforeUpload` 方法中实现了简单的文件大小验证逻辑,可以根据实际需求扩展更多规则。 4. **样式调整** - 如果有特殊布局或者交互效果的需求,可以在模板部分进一步定制化设计。 --- #### 后端集成注意事项 当后端采用 Spring Boot 架构时,通常会提供 RESTful API 接口接收前端发送过来的数据流。例如上述提到的方法 `FileUploadUtils.upload(filePath, file)` 即是一个典型的工具类实现。因此建议开发者提前确认好服务器端的具体协议约定(如 MIME 类型支持范围),以便更好地适配前后端通信流程。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值