Vue uses the Element el-upload component to step on the pit

Vue uses the Element el-upload component to step on the pit

1. Basic Use

I recently studied the el-upload component and stepped on some small pits. I wrote it down for everyone to learn

It is very common to copy the element's components directly to use, but when using the upload component, you will encounter a pitfall.

If you use upload directly, you will definitely encounter this error

And the uploaded pictures may disappear suddenly. At this time, if you don't have an interface, you have no idea why they were removed. So when there is no interface, you can only guess whether the picture disappeared because of a cross-domain error.

Finally, I got the company's address and adjusted the interface. The answer was correct: action="https://jsonplaceholder.typicode.com/posts/". This is the action parameter in element. When using html, it will call ajax, which makes the same-origin policy different and causes an error.

Generally, the company will provide an address link for converting the image into a URL format. You just need to call it and save it. However, you may encounter the need for token permissions. At this time, there is something that is rarely done. Generally, the token is not directly carried through the component, so the token must be carried through the el-upload component.

 <el-upload
            action="https://xxxx address"
            :headers="importHeaders"
          >
   </el-upload>
 
import {getToken} from '@/utils/token'
 
 
data() {
    return {
      importHeaders: {token: getToken()},
    };
  },

2. Image quantity control

 <el-upload
            action="https://security.brofirst.cn/api/common/upload"
            :headers="importHeaders"
            :limit="limit"
             :on-exceed="masterFileMax"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
 
 
 
  // How many pictures can be uploaded at most masterFileMax(files, fileList) {
        console.log(files, fileList);
        this.$message.warning(`Please upload at most ${this.limit} files.`);
    },

3. Image format restrictions/multiple images can be selected

  <el-upload
             accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
             multiple
          >
            <i class="el-icon-plus"></i>
          </el-upload>

example

   <el-upload
            action="https://xxxx"
            :headers="importHeaders"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :limit="limit"
             :on-exceed="masterFileMax"
             accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
             multiple
          >
            <i class="el-icon-plus"></i>
          </el-upload>
 
 
 
<script>
import {getToken} from '@/utils/token'
export default {
  name:'feedback',
  data() {
    return {
      importHeaders: {token: getToken()},
       images:[],
      limit:9
    };
  },
  methods: {
  //Delete the picture handleRemove(file, fileList) {
     const idx = this.images.findIndex(it=>it===file.response.data.fullurl)
     this.images.splice(idx,1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //Data after successful upload handleAvatarSuccess(response, file, fileList){
      console.log(response, file, fileList);
      if(response.code===1){
        this.images.push(response.data.fullurl)
      }
    },
    // How many pictures can be uploaded at most masterFileMax(files, fileList) {
        console.log(files, fileList);
        this.$message.warning(`Please upload at most ${this.limit} files.`);
    }
  }
};
</script> 

Supplement: Use element-ui's Upload component in the vue project

<el-upload
               v-else
               class='ensure ensureButt'
               :action="importFileUrl"
               :data="upLoadData"
               name="importfile"
               :onError="uploadError"
               :onSuccess="uploadSuccess"
               :beforeUpload="beforeAvatarUpload"
               >
               <el-button size="small" type="primary">OK</el-button>

Among them, importFileUrl is the background interface, upLoadData is the additional parameter to be uploaded when uploading files, uploadError is the callback function when the file upload fails, uploadSuccess is the callback function when the file upload is successful, and beforeAvatarUpload is the function called before uploading the file. We can judge the file type here.

data () {
    importFileUrl: 'http:dtc.com/cpy/add',
    upLoadData: {
        cpyId: '123456', 
        occurTime: '2017-08'
    }
},
methods: {
    // Callback after successful uploaduploadSuccess (response, file, fileList) {
      console.log('Upload file', response)
    },
    // Upload error uploadError (response, file, fileList) {
      console.log('Upload failed, please try again!')
    },
    // Determine the file size before uploading beforeAvatarUpload (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const extension3 = file.name.split('.')[1] === 'doc'
      const extension4 = file.name.split('.')[1] === 'docx'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!extension && !extension2 && !extension3 && !extension4) {
        console.log('The uploaded template can only be in xls, xlsx, doc, docx format!')
      }
      if (!isLt2M) {
        console.log('The uploaded template size cannot exceed 10MB!')
      }
      return extension || extension2 || extension3 || extension4 && isLt2M
    }
}

This is the end of this article about using Element el-upload component in Vue. For more relevant content about Vue Element el-upload component, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Use of vue-cli3.0+element-ui upload component el-upload
  • vue+elementUI (el-upload) image compression, default same ratio compression operation
  • Solve the problem that submit() does not work when the before-upload method of el-upload returns false in vue2.0 element-ui

<<:  How to view nginx configuration file path and resource file path

>>:  MySQL master-slave replication principle and points to note

Recommend

WeChat applet implements SMS login in action

Table of contents 1. Interface effect preview 2.u...

npm Taobao mirror modification explanation

1. Top-level usage 1. Install cnpm npm i -g cnpm ...

In-depth understanding of the use of Vue

Table of contents Understand the core concept of ...

How much data can be stored in a MySQL table?

Programmers must deal with MySQL a lot, and it ca...

100 ways to change the color of an image using CSS (worth collecting)

Preface “When it comes to image processing, we of...

Detailed explanation of the process of docker packaging Python environment

The steps of docker packaging Python environment ...

Javascript scope and closure details

Table of contents 1. Scope 2. Scope Chain 3. Lexi...

Methods to enhance access control security in Linux kernel

background Some time ago, our project team was he...

JavaScript Advanced Custom Exception

Table of contents 1. Concept 1.1 What are errors ...

Methods for optimizing Oracle database with large memory pages in Linux

Preface PC Server has developed to this day and h...

Using Openlayer in Vue to realize loading animation effect

Note: You cannot use scoped animations! ! ! ! via...

HTML hyperlinks explained in detail

Hyperlink Hyperlinks are the most frequently used ...

Detailed explanation of using MySQL where

Table of contents 1. Introduction 2. Main text 2....

How to view nginx configuration file path and resource file path

View the nginx configuration file path Through ng...

WeChat applet calculator example

WeChat applet calculator example, for your refere...