element对上传组件二次封装,vue上传下载组件的实现

前言:

      对element的上传组件进行二次封装,让他可以实现上传下载功能。

实现效果:

手动上传,不是自动,选中文件后可上传,也可清空选中文件,单个删除也是可以的

实现步骤:

1、封装好的 uploadAndDown.vue源码,  引入就好

<template>
      <el-upload
        v-if="Refresh"
        class="upload-demo"
        ref="upload"
        :action="action"
        :headers="headers"
        :multiple="multiple"
        :data="data"
        :name="name"
        :with-credentials="cookieOK"
        :show-file-list="showFileList"
        :drag="drag"
        :accept="accept"
        :list-type="listType"
        :auto-upload="autoUpload"
        :file-list="fileList"
        :disabled="is_disabled"

        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-progress="handleProgress"
        :on-exceed="handleExceed"
        :on-change="onChange"

        :before-upload="beforeUpload"
        :before-remove="beforeRemove"
        :http-request="httpRequest"
        >
        <el-button slot="trigger" type="primary" icon="el-icon-upload2">选取文件</el-button>
        <el-button style="margin-left: 10px;"
                   type="success"
                   @click="submitUploadSD"
                   :disabled="fileList.length==0"
                   :title="fileList.length==0?'请先选中文件':''"
                   icon="el-icon-upload">开始上传</el-button>
        <el-button type="danger"
                   v-if="fileList.length>0"
                   icon="el-icon-delete"
                   @click.stop="clearFiles"
                   title="清空选中文件"
                   circle></el-button>
        <el-button style="margin-left: 10px;"
                   type="primary"
                   @click.stop="downFile"
                   icon="el-icon-download">下载模板</el-button>

        <!--提示信息-->
        <div slot="tip" class="el-upload__tip" v-if="tip_text!=''">{{tip_text}}</div>
      </el-upload>

</template>

<script>
  //element的上传文件组件
  export default {
    props:{
      /**
       * 自动上传参数
       * */
      autoUpload:{ // 是否需要选取完自动上传功能
        type: Boolean,
        default: false
      },
      action:{//上传的地址
        type: String,
        default: ''
      },
      headers: {//设置上传的请求头部
        type:Object,
        default: () => {
          return {}
        }
      },
      data: {//上传时额外带的参数
        type:Object,
        default: () => {
          return {}
        }
      },
      name:{//上传的文件字段名
        type: String,
        default: 'file'
      },
      cookieOK:{//支持发送 cookie 凭证信息
        type: Boolean,
        default: true
      },
      /**
       * 公共参数
       * */
      showFileList:{//是否显示已上传文件列表
        type: Boolean,
        default: true
      },
      drag:{//是否启用拖拽上传
        type: Boolean,
        default: false
      },
      accept:{//接受文件类型-图片上传类型-不同的格式之间以逗号隔开
        type: String,
        // default:'.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        default: '.xlsx,.xls'
      },
      listType:{ // 文件列表的类型 - text/picture/picture-card
        type: String,
        default: 'text'
      },
      fileList:{//已上传的文件列表,
        type:Array,
        default: () => {
          // { 默认格式
          //   name: 'food.jpeg',
          //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
          // }
          return []
        }
      },
      is_disabled:{//是否禁止,true是禁止,false不禁止
        type: Boolean,
        default: false
      },
      multiple:{//是否可以多选
        type: Boolean,
        default: true
      },
      limit:{//最大允许上传个数
        type: Number,
        default: 30
      },

      tip_text:{//提示信息
        type: String,
        default: ''
      },
      /**
       * 手动上传参数
       * */
      needFromUpload:{ // form表单,将上传的file文件通过 formUpload  方法发送出去
        type: Boolean,
        default: false
      },


    },
    watch: {},
    data() {
      return {
        Refresh:true,//强制刷新
      }
    },
    created() {
    },
    mounted() {
    },
    methods: {
      /**
       * 上传-默认事件
       * */
      //文件列表移除文件时的钩子
      handleRemove(file, fileList) {
        console.log('当前移除的是'+file);
      },
      //点击文件列表中已上传的文件时的钩子
      handlePreview(file) {
        console.log('当前点击的是'+file);
      },
      //文件上传成功时的钩子
      handleSuccess(response, file, fileList) {
        console.log('文件上传成功');
      },
      //文件上传失败时的钩子
      handleError(err, file, fileList) {
        console.log('文件上传失败');
      },
      //文件上传时的钩子
      handleProgress(event, file, fileList) {
        console.log(file);
      },
      //文件超出个数限制时的钩子
      handleExceed(files, fileList) {
        console.log('文件超出个数限制');
      },
      //覆盖默认的上传行为,可以自定义上传的实现
      httpRequest(){

      },
      //删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止删除。
      beforeRemove(file, fileList) {
        console.log('当前删除的文件'+file);
        this.fileList.forEach((item,index)=>{
          if(item == file){
            this.fileList.splice(index,1)
          }
        })
      },

      /**
       * 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
       */
      onChange(file, fileList) {
        this.fileList = fileList;
        console.log('当前的选中文件:');
        console.log(fileList);
      },
      /**
       * 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。
       */
      beforeUpload(file) {
          console.log(file);
      },
      /**
       * 上传-自定义事件
       * */
      submitUpload() {
        this.$refs.upload.submit();
      },
      //清空已上传的文件列表(该方法不支持在 before-upload 中调用)
      clearFiles(){
        this.$refs.upload.clearFiles();
        this.fileList = [];
      },
      //取消上传某个文件
      abortFiles(file){
        this.$refs.upload.abort(file);
      },



      /**
       * 手动上传点击确认
       * */
      submitUploadSD(){
        let arr = this.fileList;
        let str = {
          fileList:arr
        }
        this.$emit('uploadFile',str);
      },
      /**
       * 下载模板点击
       * */
      downFile(){
        this.$emit('downFile');
      },
      /**
       * 手动刷新上传组件
       * */
      RefreshUpload(){
        let arr = this.fileList;
        this.Refresh = false;
        this.$nextTick(()=>{
          this.Refresh = true;
        })
      },

    },
    components: {},
    beforeDestroy() {
    }

  }
</script>

<style lang='scss' scoped>

</style>

2、调用方法:

template:

<uploadAndDown class="uploadAndDown" @uploadFile="uploadFile" @downFile="downFile"></uploadAndDown>

js部分: 这里拿到的是一个数组,不管增、删,这个数组都是对应现在选中了几个文件

      /**
       * 上传
       * */
      uploadFile(str){
        let fileList = str.fileList;
        debugger

      },
      //下载事件
      downFile(){
        console.log('点击下载按钮');
      },

css部分:

 .uploadAndDown{
    width: 91%;
    padding-right: 1%;
    float: right;
  }

相关api:

Attribute

参数说明类型可选值默认值
action必选参数,上传的地址string
headers设置上传的请求头部object
multiple是否支持多选文件boolean
data上传时附带的额外参数object
name上传的文件字段名stringfile
with-credentials支持发送 cookie 凭证信息booleanfalse
show-file-list是否显示已上传文件列表booleantrue
drag是否启用拖拽上传booleanfalse
accept接受上传的文件类型(thumbnail-mode 模式下此参数无效)string
on-preview点击文件列表中已上传的文件时的钩子function(file)
on-remove文件列表移除文件时的钩子function(file, fileList)
on-success文件上传成功时的钩子function(response, file, fileList)
on-error文件上传失败时的钩子function(err, file, fileList)
on-progress文件上传时的钩子function(event, file, fileList)
on-change文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用function(file, fileList)
before-upload上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。function(file)
before-remove删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止删除。function(file, fileList)
list-type文件列表的类型stringtext/picture/picture-cardtext
auto-upload是否在选取文件后立即进行上传booleantrue
file-list上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]array[]
http-request覆盖默认的上传行为,可以自定义上传的实现function
disabled是否禁用booleanfalse
limit最大允许上传个数number
on-exceed文件超出个数限制时的钩子function(files, fileList)-

Slot

name说明
trigger触发文件选择框的内容
tip提示说明文字

Methods

方法名说明参数
clearFiles清空已上传的文件列表(该方法不支持在 before-upload 中调用)
abort取消上传请求( file: fileList 中的 file 对象 )
submit手动上传文件列表

 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue2中,对于element-ui组件二次封装,可以按照以下步骤进行: 1. 需求分析:明确需要封装element-ui组件,以及需要添加的功能和配置项。 2. 创建父组件:编写父组件的template和script代码,其中template中调用封装组件,script中定义需要传递给封装组件的props属性。 3. 创建封装组件:编写封装组件的template和script代码。在template中使用element-ui组件,并根据需要进行样式和布局的调整。在script中定义props属性,接收父组件传递的值,并监听element-ui组件的事件,触发update事件给父组件。 4. 通过临时变量传递值:由于父组件传递给封装组件的props不能直接作为封装组件的v-model属性传递给element-ui组件,所以需要在封装组件中定义一个临时变量来存储值,并将该变量与element-ui组件进行绑定。 5. 完成打通:在封装组件中监听中间件,接收到element-ui组件的update事件后,再将该事件传递给父组件。 总结来说,Vue2中对于element-ui组件二次封装,需要创建父组件封装组件,通过props属性传递值,并在封装组件中监听element-ui组件的事件并触发update事件给父组件。同时,需要使用临时变量来传递值给element-ui组件。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Vue3+ts+element-plus 组件二次封装-- 页脚分页el-pagination的二次封装](https://blog.csdn.net/cs492934056/article/details/128096257)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值