在列表上面上传数据,话不多说,直接上代码

背景是用了element-plus vue3

const { proxy } = getCurrentInstance() as any
<el-table-column label="封面" align="center" prop="url" width="300">
  <template #default="scope">
    <el-upload
      :ref="`${scope.row.id}_upload`"
      :key="scope.row.id"
      class="avatar-uploader"
      :headers="uploadHeaders"
      :auto-upload="false"
      :data="scope.row"
      :on-change="(file,fileList)=>{
        return handleFileChange(file,scope.row,fileList)
      }"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-exceed="(file)=>{
        return handleExceed(file,scope.row)
       }"      
      :limit="1"
    >
      <template v-if="scope.row.url">
        <img :src="scope.row.url" class="avatar" style="width:100px"/>
        <div class="upload-handle" @click.stop>
          <div  class="handle-icon" @click="handleDelete(scope.row)">
            <Icon icon="ep:delete" />
          </div>
          <div  class="handle-icon" @click="handleUploadUpdate(scope.row)">
            <Icon icon="ep:edit" />
          </div>
        </div>
      </template>
      <i v-else class="el-icon-plus avatar-uploader-icon" style="width:100px;higth:100px">
        <Icon icon="ep:plus" />
      </i>
    </el-upload>
  </template>

</el-table-column>
编辑事件
const handleUploadUpdate=(row)=>{
  proxy.$refs[`${row.id}_upload`].$el.querySelector('input[type=file]').click()
}

const handleExceed=(files,row)=>{
  proxy.$refs[`${row.id}_upload`].clearFiles();
  const file = files[0];
  proxy.$refs[`${row.id}_upload`].handleStart(file);
}

注意点,1 在on-change事件中,要求额外添加的参数,并且在on-change连接后台服务

               2 图片在有蒙层的作用下要求自动触发上传,这里做了两个操作

                 2.1 是动态加了ref 

                 2.2 是在handleUploadUpdate 事件中通过ref去触发的

              3 添加了on-exceed 事件,防止on-change事件只调用一次

        

       

更多推荐