Vue2 encapsulates a file upload component

Series Article Directory

In the daily development process, there are many times when we need to use the function of uploading files. For a large-scale project, we need to reuse file uploading. Share it with everyone here~


提示:这里只能上传word,pdf,png等格式


foreword

提示:这里可以添加本文要记录的大概内容:

For example: use component encapsulation to achieve flexibility and reusability.


提示:以下是本篇文章正文内容,下面案例可供参考

1. What should be paid attention to in component packaging?

  1. Component thinking: Components should be independent and reusable components, and should follow the principle of single responsibility, and divide the functions of components as carefully as possible.
  2. API design: The API design of the component should be reasonable, taking into account the customizability and ease of use of the component. The necessary configuration items and event callbacks should be provided as much as possible, while avoiding too many APIs, resulting in an overly complex API.
  3. Life cycle: The life cycle of components should be used reasonably, especially for components that need to interact with the outside, attention should be paid to the timing of the life cycle so that corresponding operations can be performed in different stages of the component.
  4. Component communication: Component communication is an important issue in componentized development. Vue provides a variety of communication methods, including props, events, emit, emit,emiton、 p a r e n t 、 parent、 p a rent , children , provide, inject , etc. In the design of components, it is necessary to consider the communication between components and use these communication methods reasonably.
  5. Style and layout: The style and layout of the component should be separated from the function of the component as much as possible to prevent the style and layout from affecting the function and logic of the component.
  6. Testing: After the component packaging is completed, sufficient testing is required, including unit testing and integration testing, to ensure the quality and stability of the component.

2. Use steps

1. The el-upload component in elementui is used here

The code is as follows (example):

<el-upload class="upload-demo" :multiple="multiple" action="#" :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :before-upload="beforeUpload" accept=".xlsx,.docx,.pdf,.png" :http-request="UploadFile" :limit="limit" :on-exceed="handleExceed" :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传word/pdf/png文件</div>
</el-upload>

2. Method content

The code is as follows (example):

// 上传的时候 我需要做一些什么是
    async UploadFile(file) {
    
    
      let Flag =
        this.fileList &&
        this.fileList.some(item => {
    
    
          if (file.file.name === item.name) {
    
    
            this.$message.error('文件名称重复')
            return true
          }
        })
      if (!Flag) {
    
    
        this.fileList.push(file.file)
      } else {
    
    
        this.fileList = this.fileList.slice(0, this.fileList.length)
      }
    },

    beforeUpload(file) {
    
    
      // console.log(file.name, '检查大小 格式')
    },
    // 文件移除
    handleRemove(file, fileList) {
    
    
      // console.log('文件移除')
      this.fileList = this.fileList.filter(item => {
    
    
        return item.uid != file.uid
      })
    },
    handlePreview(file) {
    
    
      // console.log(file, 'handlePreview')
    },
    handleExceed(files, fileList) {
    
    
      this.$message.warning(`当前限制选择 1 个文件,共选择了 ${
    
    files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
    
    
      return this.$confirm(`确定移除 ${
    
    file.name}?`)
    },
    clearFileList() {
    
    
      this.fileList = []
    }
  }

3. All codes (detailed)

The code is as follows (example):

<template>
  <el-upload class="upload-demo" :multiple="multiple" action="#" :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :before-upload="beforeUpload" accept=".xlsx,.docx,.pdf,.png" :http-request="UploadFile" :limit="limit" :on-exceed="handleExceed" :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传word/pdf/png文件</div>
  </el-upload>
</template>
<script>
export default {
    
    
  props: {
    
    
    limit: {
    
    
      type: Number,
      default: 3
    },
    multiple: {
    
    
      type: Boolean,
      default: false
    }
  },
  data() {
    
    
    return {
    
    
      fileList: []
    }
  },
  watch: {
    
    
    fileList: {
    
    
      handler() {
    
    
        // console.log('000')
        this.$emit('fileList', this.fileList)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    
    
    // 上传的时候 我需要做一些什么是
    async UploadFile(file) {
    
    
      let Flag =
        this.fileList &&
        this.fileList.some(item => {
    
    
          if (file.file.name === item.name) {
    
    
            this.$message.error('文件名称重复')
            return true
          }
        })
      if (!Flag) {
    
    
        this.fileList.push(file.file)
      } else {
    
    
        this.fileList = this.fileList.slice(0, this.fileList.length)
      }
    },

    beforeUpload(file) {
    
    
      // console.log(file.name, '检查大小 格式')
    },
    // 文件移除
    handleRemove(file, fileList) {
    
    
      // console.log('文件移除')
      this.fileList = this.fileList.filter(item => {
    
    
        return item.uid != file.uid
      })
    },
    handlePreview(file) {
    
    
      // console.log(file, 'handlePreview')
    },
    handleExceed(files, fileList) {
    
    
      this.$message.warning(`当前限制选择 1 个文件,共选择了 ${
    
    files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
    
    
      return this.$confirm(`确定移除 ${
    
    file.name}?`)
    },
    clearFileList() {
    
    
      this.fileList = []
    }
  }
}
</script>
<style scoped>
::v-deep .el-upload__tip {
    
    
  margin-top: -7px !important;
  margin-right: 30px !important;
}
</style>

Summarize

For example: the above is all the content of the subcomponents. The parent component can be screened or added according to actual needs, and the specific project application needs to be based on the actual situation. After sharing, if there are any functional defects, everyone is welcome to optimize and criticize and correct.

Supongo que te gusta

Origin blog.csdn.net/weixin_48211022/article/details/129751532
Recomendado
Clasificación