element-plus实现图片上传

19 篇文章 0 订阅
6 篇文章 0 订阅
<el-form-item label="头像" label-width="80px">
             <el-upload
                class="avatar-uploader"
                :action="`${path}/fileUploadAndDownload/upload`"
                :headers="{ 'x-token': userStore.token }"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                v-model="userInfo.headerImg"
              >
                <img v-if="userInfo.headerImg" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
             </el-upload>
</el-form-item>

这里action是api的路径,headers是token

2.在script中写成功的回调以及失败的回调函数,代码如下

// 图片上传成功的函数
const uploadSuccess = (res, upload)=> {
  console.log(res)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '上传成功'
        })
        imageUrl.value = URL.createObjectURL(upload.raw)
        userInfo.value.headerImg = res.data.file.url
      } else {
        ElMessage({
          type: 'warning',
          message: res.msg
        })
      }
}
//图片上传失败的回调
const uploadError = ()=> {
      ElMessage({
        type: 'error',
        message:'上传失败'
      })
}

3.数据的声明

const userInfo = ref({
  headerImg: '',
})
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
element-plus 是一款基于 Vue.js 的组件库,可以方便地实现多个图片上传功能。 首先,我们需要在项目中安装并引入 element-plus 组件库。可以通过 npm 或者 yarn 进行安装,然后在项目的主文件中引入 element-plus 的样式文件和所需的组件,例如: ```js import { ElUpload, ElButton } from 'element-plus'; import 'element-plus/lib/theme-chalk/index.css'; ``` 接下来,在 Vue 组件中使用 ElUpload 组件来实现图片上传。我们可以使用 v-for 指令循环渲染多个上传区域,每个区域都有一个独立的上传按钮和对应的图片显示区域。可以在模板中插入以下代码: ```html <template> <div> <div v-for="uploadItem in uploadItems" :key="uploadItem.id"> <el-upload class="upload" :action="uploadItem.action" :limit="uploadItem.limit" :on-success="handleUploadSuccess" > <el-button size="small" type="primary">选择图片</el-button> </el-upload> <div class="image-list"> <img v-for="url in uploadItem.imageList" :key="url" :src="url" /> </div> </div> </div> </template> ``` 在 data 中定义一个数组 uploadItems,用来存储每个上传区域的相关配置信息,包括上传地址、上传限制等。可以在 created 钩子函数中初始化 uploadItems 数组: ```js export default { data() { return { uploadItems: [ { id: 1, action: '/upload', limit: 3, imageList: [] }, { id: 2, action: '/upload', limit: 5, imageList: [] }, // 可以根据需要继续添加更多的上传区域配置 ] }; }, // ... } ``` 最后,实现 handleUploadSuccess 方法,在上传成功后将图片的 URL 添加到对应的 uploadItem.imageList 数组中: ```js export default { // ... methods: { handleUploadSuccess(response, file, uploadItem) { uploadItem.imageList.push(response.url); } } } ``` 通过以上方法,在页面中就可以实现多个图片上传功能了。每个上传区域都独立管理自己的图片列表,方便实现一次性上传多个图片的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值