el-upload 组件上传/移除/报错/预览文件,预览图片、pdf 等功能

页面代码

dialog.vue

<!-- 上传文件 -->
<template>
  <el-dialog
    title="上传文件"
    :visible.sync="dialogVisible"
    width="60%"
    top="6vh"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <ele-form
      ref="submitRef"
      v-model="formData"
      inline
      :form-desc="formDesc"
      :request-fn="handleSubmit"
      :is-show-submit-btn="true"
      :is-show-cancel-btn="true"
      submit-btn-text="确定"
      :is-show-error-notify="false"
      @cancel="handleClose"
    >
      <template v-slot:attachmentList>
        <el-upload
          ref="uploadRef"
          v-loading="uploadLoading"
          class="upload_demo"
          list-type="picture-card"
          :accept="fileTypeList.join(',')"
          action="/supervise_basic/upload/oss/fileupload"
          name="files"
          multiple
          :file-list="fileList"
          :headers="{ 'X-Token': getToken() }"
          :data="{ relativePath: 'SCWS/' }"
          :on-success="onSuccessHandler"
          :on-error="onErrorHandler"
          :on-remove="onRemoveHandler"
          :before-upload="beforeUploadHandler"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{ file }" class="el_upload_preview_list">
            <!-- pdf 文件展示文件名 (【20240304-补充】如果需要判断别的文件类型可判断 v-if="['.pdf', '.doc', '.docx'].includes(file.name.slice(file.name.lastIndexOf('.')))") -->
            <!-- 【20240304-补充】如果需要判断别的文件类型可判断 v-if="['.pdf', '.doc', '.docx'].includes(file.name.slice(file.name.lastIndexOf('.')))" -->
            <div v-if="['application/pdf'].includes(file.raw.type)" class="pdfContainer">
              {{ file.name }}
            </div>
            <!-- 图片预览 -->
            <el-image
              v-else
              :id="'image' + file.uid"
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              :preview-src-list="[file.url]"
            />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in" />
              </span>
              <span class="el-upload-list__item-delete" @click="onRemoveHandler(file)">
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
          <template v-slot:tip>
            <div class="el_upload_tip">
              仅支持上传{{ fileTypeList.join('/') }}格式文件,且不超过{{ fileMaxSize }}MB。
            </div>
          </template>
        </el-upload>
      </template>
    </ele-form>
  </el-dialog>
</template>

<script>
import _ from 'lodash.clonedeep'
import { getToken } from '@/utils/tool'
import { uploadBloodFile } from '@/api/blood_api.js'

export default {
  name: 'UploadFileDialog',
  components: {},

  data() {
    return {
      dialogVisible: true,
      rowData: {},
      formData: {
        attachmentList: []
      },
      uploadLoading: false,
      fileTypeList: ['.png', '.jpg', '.jpeg', '.pdf'],
      fileMaxSize: 5,
      fileList: [],
      getToken
    }
  },

  computed: {
    formDesc() {
      return {
        xbrq: {
          type: 'date',
          layout: 24,
          label: '日期',
          required: true,
          attrs: {
            valueFormat: 'yyyy-MM-dd'
          },
          class: {
            textareaTop: true
          },
          style: {
            marginBottom: '10px'
          }
        },
        attachmentList: {
          type: 'upload',
          layout: 24,
          label: '上传文件',
          required: true
        }
      }
    }
  },

  watch: {
    dialogVisible() {
      this.$refs.submitRef &&
        this.$refs.submitRef.$refs.form &&
        this.$refs.submitRef.$refs.form.clearValidate()
    }
  },

  created() {
    const list = []
    this.fileTypeList.forEach((item) => {
      list.push(item, item.toUpperCase())
    })
    this.fileTypeList = [...list]
  },

  methods: {
    open(rowData) {
      console.log('rowData----', rowData)
      this.rowData = _(rowData)

      this.dialogVisible = true
    },

    beforeUploadHandler(file) {
      const ext = file.name.substring(file.name.lastIndexOf('.'))
      const isLt = file.size / 1024 / 1024 < this.fileMaxSize

      if (!this.fileTypeList.includes(ext)) {
        this.$message.error(`请上传${this.fileTypeList.map((item) => item)}格式的文件!`)
        return false // 会调用 on-remove 钩子
      } else if (!isLt) {
        this.$message.error('上传文件大小不能超过 5MB!')
        return false // 会调用 on-remove 钩子
      } else {
        this.uploadLoading = true
        return true
      }
    },

    onRemoveHandler(file, fileList) {
      /**
       * fileList 有无值取决于是上传失败调用 on-remove 钩子,还是手动点击删除按钮删除文件,详细解释如①②:
       *    ① 如果文件上传失败(before-upload 中return false)会自动调用 on-remove 钩子(不用我们自己处理删除文件),此时第二个参数 fileList 有值(为数组);
       *    ② 如果手动点击删除文件按钮删除,此时 fileList 是没有的,为 undefined;
       *    因此通过 fileList 来判断是否执行 on-remove 钩子中我们自己处理移除文件(避免:已经上传了N张图片后,上传不符合要求的图片时调用当前方法导致第 N-1 张图片被删除)
       */
      if (fileList) return

      const { uploadFiles } = this.$refs.uploadRef
      uploadFiles.splice(
        uploadFiles.findIndex((item) => item.uid === file.uid),
        1
      )
      this.formData.attachmentList.splice(
        this.formData.attachmentList.findIndex(
          (item) => item.uid === file.uid && item.filename === file.name
        ),
        1
      )
      this.$refs.submitRef &&
        this.$refs.submitRef.$refs.form &&
        this.$refs.submitRef.$refs.form.validateField('attachmentList')
    },

    // eslint-disable-next-line handle-callback-err
    onErrorHandler(err, file, fileList) {
      this.uploadLoading = false
      this.$message.error(`${file.name}文件上传失败,请重新上传!`)
    },

    // 文件上传成功
    onSuccessHandler(response, file) {
      this.uploadLoading = false
      console.log('response----', response)
      const fileList = response.data.fileUploadInfoList
        ? response.data.fileUploadInfoList.map((item) => {
            return {
              filename: item.filename,
              saved_filename: item.path,
              filetype: item.fileType,
              uid: file.uid
            }
          })
        : []
      this.formData.attachmentList.push(...fileList)
      // 部分表单校验
      this.$refs.submitRef &&
        this.$refs.submitRef.$refs.form &&
        this.$refs.submitRef.$refs.form.validateField('attachmentList')
    },

    // 预览 pdf、图片
    handlePictureCardPreview(file) {
      // 预览pdf
      if (['application/pdf'].includes(file.raw.type)) {
        window.open(file.url)
        return
      }
      
      // // 【20240304-补充】预览 pdf、doc、docx 文档
      // const fileType = file.name.slice(file.name.lastIndexOf('.'))
      // console.log('fileType----', fileType)
      // if (['.pdf', '.doc', '.docx'].includes(fileType)) {
      //   window.open(file.url)
      // }
    
      // 预览文件
      const imageDom = document.getElementById('image' + file.uid)
      imageDom && imageDom.click()
    },

    handleSubmit() {
      this.$refs.submitRef.validate().then((valid) => {
        const { id, voucher_no } = this.rowData
        const { attachmentList, xbrq } = this.formData
        const params = {
          id,
          voucher_no,
          xgws: attachmentList.map((item) => {
            return {
              wsmc: item.filename,
              wsdz: item.saved_filename,
              xbrq: xbrq
            }
          })
        }
        uploadBloodFile(params).then((res) => {
          this.$common.CheckCode(res, res.msg || '上传成功', () => {
            this.handleClose()
            this.$emit('update')
          })
        })
      })
    },

    handleClose() {
      this.rowData = {}
      this.fileList = []
      for (const key in this.formData) {
        if (this.formData[key] && this.formData[key].constructor === Array) {
          this.formData[key] = []
        } else if (this.formData[key] && this.formData[key].constructor === Object) {
          this.formData[key] = {}
        } else {
          this.formData[key] = ''
        }
      }
      this.dialogVisible = false
    }
  }
}
</script>

<style lang='scss' scoped>
@import '@/styles/dialog-style.scss';
</style>

样式代码

@/styles/dialog-style.scss

::v-deep .el-dialog {
  min-width: 760px;
  .el-dialog__header {
    font-weight: 700;
    border-left: 3px solid #00a4ff;
  }
  .el-dialog__headerbtn {
    top: 13px;
  }

  .ele-form {
    .el-form-item__error {
      top: 75%;
    }
    .el-form-item {
      margin-bottom: 0;
    }
    .ele-form-btns {
      width: 100%;
      .el-form-item__content {
        text-align: right;
      }
    }

    // ele-form 表单项为 textarea 时,当前表单项和上一个表单项校验提示文字位置调整
    .textareaTop {
      & + .el-form-item__error {
        // 上一个表单项检验提示文字位置
        top: 65% !important;
      }
    }
    .currentTextarea {
      & + .el-form-item__error {
        // 当前 textarea 表单项检验提示文字位置
        top: 92% !important;
      }
    }
  }

  .upload_demo {
    margin-top: 8px;
    & + .el-form-item__error {
      top: 156px !important;
    }
  }
}

.dialog_section_title {
  margin: 10px -20px;
  padding: 10px 20px;
  // background-color: #eee;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  border-left: 3px solid #00a4ff;
  font-weight: 700;
  text-align: left;
}

.noData {
  padding: 10px 0;
  text-align: center;
  color: #ccc;
}

.el_upload_tip {
  margin-top: 15px;
  line-height: 20px;
  text-align: left;
  color: red;
}

.el_upload_preview_list {
  height: 100%;
  // el-uplaod组件卡片预览类型预览pdf样式
  .pdfContainer {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.blue-theme {
  .dialog_section_title {
    border-top: 1px solid #202936;
    border-bottom: 1px solid #202936;
  }
}

.night-theme {
  .dialog_section_title {
    border-top: 1px solid #202936;
    border-bottom: 1px solid #202936;
  }
}

页面展示

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

【注意】

  • 此文档中不涉及编辑图片
  • 【20240304-补充】中的 .doc .docx 文档预览时是直接 下载文件

【补充】编辑图片 - 移除时注意(还有问题,编辑时一次上传多个文件然后删除之前已有文件,新上传的文件全没了 - 和 this.fileList 有关)

注意代码 - 调整的代码

/**** data 中代码变化 ****/
data() {
  return {
    // ...
    editFileInitLength: 0 // 编辑前已有文件数量
  }
}

/**** methods 中代码变化 ****/
// 打开弹框 - 编辑时 要给 this.fileList 也赋初始值
open(type, rowData) {
  this.dialogType = type
  this.rowData = _(rowData)
  if (type === 'edit') {
    for (const key in this.formDesc) {
      this.$set(this.formData, key, _(rowData[key])) // 【主要代码】这里注意要浅拷贝(避免 fileList 属性值为数组移除文件时修改rowData中数据)
    }
    const { fileList } = rowData
    if (fileList && fileList.length) {
      // 【主要代码】this.fileList 也赋初始值 用于编辑时回显已有照片
      this.fileList = fileList.map((item) => {
        return {
          name: item.wjmc,
          url: this.configData.mon_oss_filepath + item.wjlj // configData 为系统参数,从 vuex 中取
        }
      })
      this.editFileInitLength = this.fileList.length
    }
  }
  this.dialogVisible = true
},

// 移除文件方法中代码调整
onRemoveHandler(file, fileList) {
  if (fileList) return
  /**
   * 编辑移除文件:判断要删除的文件是否为编辑前已有文件(根据当前删除文件索引判断)
   *    是 → 删除编辑前已有文件
   *    否 → 删除新上传文件
   */
  // 获取索引(用注释掉的代码)
  const currentIndex = this.formData.fileList.findIndex(
    (item) => item.wjlj === file.url.replace(this.configData.mon_oss_filepath, '')
  )
  // const currentIndex = this.formData.fileList.findIndex( // file.url 是已有文件路径;file.response.data.fileUploadInfoList[0].path 是新上传文件路径
  //   (item)=>
  //     item.wjlj === file.url.replace(this.configData.mon_oss_filepath, '') ||
  //     item.wjlj ===
  //       (file.response &&
  //         file.response.data &&
  //         file.response.data.fileUploadInfoList &&
  //         file.response.data.fileUploadInfoList.length &&
  //         file.response.data.fileUploadInfoList[0].path)
  // )
  
  // currentIndex 不为 -1 则列表中有要删除的文件(编辑新增都兼容) → 根据当前索引是否小于编辑前已有文件列表长度判断是要删除已有文件还是删除新上传文件
  if (currentIndex >= 0) {
    if (currentIndex < this.editFileInitLength) {
      // 编辑前已有文件:删除 fileList、formData.fileList 中相关数据 并将 “编辑前已有文件数量” 减1
      this.fileList.splice(currentIndex, 1)
      this.editFileInitLength--
    } else {
      // 新上传的文件:删除 uploadFiles、formData.fileList 中相关数据
      const { uploadFiles } = this.$refs.uploadRef
      uploadFiles.splice(currentIndex, 1)
    }
    this.formData.fileList.splice(currentIndex, 1)
  }
  console.log('currentIndex----', currentIndex)
  // 【主要代码】以上代码为主要代码,文件上传成功后保存的 uid 其实就没用了
  
  // 以下代码是不兼容编辑的移除文件(现已无用)
  return
  if (fileList) return

  const { uploadFiles } = this.$refs.uploadRef
  uploadFiles.splice(
    uploadFiles.findIndex((item) => item.uid === file.uid),
    1
  )
  this.formData.fileList.splice(
    this.formData.fileList.findIndex(
      (item) => item.uid === file.uid && item.wjmc === file.name
    ),
    1
  )
  // 部分表单校验
  // this.$refs.submitRef &&
  //   this.$refs.submitRef.$refs.form &&
  //   this.$refs.submitRef.$refs.form.validateField('fileList')
},

完整代码

<!-- 新增、编辑弹框 -->
<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="50%"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <ele-form
      ref="submitRef"
      v-model="formData"
      inline
      :disabled="dialogType === 'detail'"
      :form-desc="formDesc"
      :is-show-submit-btn="false"
      :is-show-error-notify="false"
      :request-fn="handleSubmit"
      :is-show-semicolon="false"
      @cancel="handleClose"
    >
      <template #fileList>
        <el-upload
          ref="uploadRef"
          v-loading="uploadLoading"
          class="upload_demo"
          list-type="picture-card"
          :accept="fileTypeList.join(',')"
          action="/supervise_basic/upload/oss/fileupload"
          name="files"
          multiple
          :file-list="fileList"
          :headers="{ 'X-Token': getToken() }"
          :data="{ relativePath: 'XQLGFJ/' }"
          :on-success="onSuccessHandler"
          :on-error="onErrorHandler"
          :on-remove="onRemoveHandler"
          :before-upload="beforeUploadHandler"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{ file }" class="el_upload_preview_list">
            <!-- pdf、doc、docx 文件展示文件名 -->
            <div
              v-if="['.pdf', '.doc', '.docx'].includes(file.name.slice(file.name.lastIndexOf('.')))"
              class="pdfContainer"
            >
              {{ file.name }}
            </div>
            <!-- 图片预览 -->
            <el-image
              v-else
              :id="'image' + file.uid"
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              :preview-src-list="[file.url]"
            />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in" />
              </span>
              <span class="el-upload-list__item-delete" @click="onRemoveHandler(file)">
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
          <template v-slot:tip>
            <div class="el_upload_tip">
              仅支持上传{{ fileTypeList.join('/') }}格式文件,且不超过{{ fileMaxSize }}MB。
            </div>
          </template>
        </el-upload>
      </template>
    </ele-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="handleSubmit">提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import _ from 'lodash.clonedeep'
import { getToken } from '@/utils/auth'
import { addItemsDemands, updateItemsDemands } from '@/api/model/need-manage'
import { operationFormDesc } from '../constant/formList'

export default {
  name: 'OperationDialog',
  components: {},

  data() {
    return {
      dialogVisible: false,
      dialogType: '',
      formData: {
        fileList: []
      },
      rowData: {},
      loading: false,
      fileList: [],
      fileMaxSize: 5,
      fileTypeList: ['.png', '.jpg', '.jpeg', '.pdf', '.doc', '.docx'],
      uploadLoading: false,
      getToken,
      editFileInitLength: 0 // 【主要代码】编辑前已有文件数量
    }
  },

  computed: {
    ...mapGetters(['userCode', 'configData']), // 【主要代码】
    title() {
      const obj = {
        add: '新增',
        edit: '编辑'
      }
      return obj[this.dialogType]
    },
    submitAx() {
      const obj = {
        add: addItemsDemands,
        edit: updateItemsDemands
      }
      return obj[this.dialogType]
    },
    formDesc() {
      return operationFormDesc(this)
    }
  },

  watch: {
    dialogVisible() {
      this.$refs.submitRef &&
        this.$refs.submitRef.$refs.form &&
        this.$refs.submitRef.$refs.form.clearValidate()
    }
  },

  created() {},

  methods: {
    open(type, rowData) {
      this.dialogType = type
      this.rowData = _(rowData)
      if (type === 'edit') {
        for (const key in this.formDesc) {
          this.$set(this.formData, key, _(rowData[key])) // 【主要代码】
        }
        const { fileList } = rowData
        if (fileList && fileList.length) {
          // 【主要代码】用于编辑时回显已有照片
          this.fileList = fileList.map((item) => {
            return {
              name: item.wjmc,
              url: this.configData.mon_oss_filepath + item.wjlj
            }
          })
          this.editFileInitLength = this.fileList.length
        }
      }
      this.dialogVisible = true
    },
    beforeUploadHandler(file) {
      const ext = file.name.substring(file.name.lastIndexOf('.'))
      const isLt = file.size / 1024 / 1024 < this.fileMaxSize

      if (!this.fileTypeList.includes(ext)) {
        this.$message.error(`请上传${this.fileTypeList.map((item) => item)}格式的文件!`)
        return false
      } else if (!isLt) {
        this.$message.error('上传文件大小不能超过 5MB!')
        return false
      } else {
        this.uploadLoading = true
        return true
      }
    },

    // 【主要代码】
    onRemoveHandler(file, fileList) {
      if (fileList) return
      /**
       * 编辑移除文件:判断要删除的文件是否为编辑前已有文件(根据当前删除文件索引判断)
       *    是 → 删除编辑前已有文件
       *    否 → 删除新上传文件
       */
      // 获取索引(用注释掉的代码)
      const currentIndex = this.formData.fileList.findIndex(
        (item) => item.wjlj === file.url.replace(this.configData.mon_oss_filepath, '')
      )
      // const currentIndex = this.formData.fileList.findIndex( // file.url 是已有文件路径;file.response.data.fileUploadInfoList[0].path 是新上传文件路径
	  //   (item)=>
	  //     item.wjlj === file.url.replace(this.configData.mon_oss_filepath, '') ||
	  //     item.wjlj ===
	  //       (file.response &&
	  //         file.response.data &&
	  //         file.response.data.fileUploadInfoList &&
	  //         file.response.data.fileUploadInfoList.length &&
	  //         file.response.data.fileUploadInfoList[0].path)
	  // )
	  
      // currentIndex 不为 -1 则列表中有要删除的文件(编辑新增都兼容) → 根据当前索引是否小于编辑前已有文件列表长度判断是要删除已有文件还是删除新上传文件
      if (currentIndex >= 0) {
        if (currentIndex < this.editFileInitLength) {
          // 编辑前已有文件:删除 fileList、formData.fileList 中相关数据 并将 “编辑前已有文件数量” 减1
          this.fileList.splice(currentIndex, 1)
          this.editFileInitLength--
        } else {
          // 新上传的文件:删除 uploadFiles、formData.fileList 中相关数据
          const { uploadFiles } = this.$refs.uploadRef
          uploadFiles.splice(currentIndex, 1)
        }
        this.formData.fileList.splice(currentIndex, 1)
      }
      console.log('currentIndex----', currentIndex)
      // 【主要代码】以上代码为主要代码,文件上传成功后保存的 uid 其实就没用了

      // 以下代码是不兼容编辑的移除文件(现已无用)
      return
      if (fileList) return

      const { uploadFiles } = this.$refs.uploadRef
      uploadFiles.splice(
        uploadFiles.findIndex((item) => item.uid === file.uid),
        1
      )
      this.formData.fileList.splice(
        this.formData.fileList.findIndex(
          (item) => item.uid === file.uid && item.wjmc === file.name
        ),
        1
      )
      // 部分表单校验
      // this.$refs.submitRef &&
      //   this.$refs.submitRef.$refs.form &&
      //   this.$refs.submitRef.$refs.form.validateField('fileList')
    },

    // eslint-disable-next-line handle-callback-err
    onErrorHandler(err, file, fileList) {
      this.uploadLoading = false
      this.$message.error(`${file.name}文件上传失败,请重新上传!`)
    },

    // 文件上传成功
    onSuccessHandler(response, file) {
      this.uploadLoading = false
      console.log('response----', response)
      const fileList = response.data.fileUploadInfoList
        ? response.data.fileUploadInfoList.map((item) => {
            return {
              wjmc: item.filename,
              wjlj: item.path,
              wjgs: item.fileType,
              uid: file.uid
            }
          })
        : []
      this.formData.fileList.push(...fileList)
      // 部分表单校验
      // this.$refs.submitRef &&
      //   this.$refs.submitRef.$refs.form &&
      //   this.$refs.submitRef.$refs.form.validateField('fileList')
    },

    // 预览 pdf、图片
    handlePictureCardPreview(file) {
      console.log('file----', file)

      // 预览 pdf、doc、docx 文档
      const fileType = file.name.slice(file.name.lastIndexOf('.'))
      console.log('fileType----', fileType)
      if (['.pdf', '.doc', '.docx'].includes(fileType)) {
        window.open(file.url)
      }
      // 预览文件
      const imageDom = document.getElementById('image' + file.uid)
      imageDom && imageDom.click()
    },

    handleSubmit() {
      this.$refs.submitRef.validate().then((valid) => {
        console.log('111----', 111)
        this.loading = true
        this.submitAx({
          ...this.formData,
          jsr: this.userCode,
          ...(this.dialogType === 'edit'
            ? {
                xlh: this.rowData.xlh,
                xqzt: this.rowData.xqzt
              }
            : {})
        })
          .then((res) => {
            console.log('res----', res)
            this.$message(`${this.title}成功`)
            this.handleClose()
            this.$emit('update')
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    handleClose() {
      this.rowData = {}
      this.fileList = []
      for (const key in this.formData) {
        if (this.formData[key] && this.formData[key].constructor === Array) {
          this.formData[key] = []
        } else if (this.formData[key] && this.formData[key].constructor === Object) {
          this.formData[key] = {}
        } else {
          this.formData[key] = ''
        }
      }
      this.dialogVisible = false
    }
  }
}
</script>

<style lang='scss' scoped>
.el_upload_preview_list {
  height: 100%;
  // el-uplaod组件卡片预览类型预览pdf样式
  .pdfContainer {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Vue和Element UI表格中实现行内el-upload文件添加/多文件上传,您可以按照以下步骤进行操作: 1. 在表格中添加一个列,用于上传文件。您可以使用Element UI的el-upload组件实现文件上传功能。例如: ```html <el-table-column label="上传文件"> <template slot-scope="scope"> <el-upload :action="uploadUrl" :on-success="handleSuccess" :file-list="scope.row.fileList" multiple > <el-button size="small" type="primary">点击上传</el-button> </el-upload> </template> </el-table-column> ``` 在上面的示例中,我们使用了Element UI的el-upload组件,并将它嵌套在表格列的模板中。我们还将文件列表绑定到scope.row.fileList,这样每一行都有自己的文件列表。 2. 在Vue组件中,你需要为el-upload组件提供上传URL和处理成功的方法。例如: ```javascript export default { data() { return { uploadUrl: '/api/upload', }; }, methods: { handleSuccess(response, file, fileList) { // 处理上传成功的文件 }, }, }; ``` 在上面的示例中,我们将上传URL设置为/api/upload,并提供了一个handleSuccess方法来处理成功上传文件。 3. 如果您想要支持多文件上传,只需要在el-upload组件上添加multiple属性即可。 ```html <el-upload :action="uploadUrl" :on-success="handleSuccess" :file-list="scope.row.fileList" multiple > ``` 这样就可以在Vue和Element UI表格中实现行内el-upload文件添加/多文件上传了。请注意,这只是一个基本的示例,您可以根据您的实际需求进行更改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值