Vue encapsulation component upload picture component

Vue encapsulation component upload picture component

This article example shares the specific code of the vue upload picture component for your reference. The specific content is as follows

Not uploaded status

Upload Status

Other status (view/delete)

Custom component file name - Here it is called UploadImg.vue

<template>
  <div>
    <el-form>
      <!-- :on-change="uploadFile" -->
      <el-upload
        :limit="limit" //The maximum number of uploads allowed action
        accept="image/*" //Accept upload:on-change="uploadFile" //Function when file status changeslist-type="picture-card" //File list type:auto-upload="false" //Whether to upload immediately after selecting a file:file-list="fileList" //Virtual file array:on-exceed="handleExceed" //Function when the number of files exceeds the limit:on-preview="handlePictureCardPreview" //Function when clicking on an uploaded file in the file list:on-remove="handleRemove" //Function when removing a file from the file listref="upload"
        class="avatar-uploader"
        :class="{hide:showUpload}" //Used to hide the upload button after reaching the maximum limit: disabled="disabled" //To view the upload failure process>
        <i class="el-icon-plus"></i>
      </el-upload>
      //View the image <el-dialog width="30%" :visible.sync="dialogVisible">
        <img width="100%" :src="imgUrl.url" alt />
      </el-dialog>
      //If you don't need to upload directly, but need to click a button to upload the image, please open this method //Change on-change in the el-upload tag above to http-request method<!-- <Button text="Upload" type="add_u" style="margin-top: 10px;" @click.native="submitUpload"></Button> -->
    </el-form>
  </div>
</template>

<script>
//Introduce the upload image interface import { uploadImg } from "@/api/public/api";
export default {
  props: {
    limit: Number,
    fileList: Array,
    disabled: Boolean,
  },
  data() {
    return {
      showUpload: false, //Close the upload button after controlling the maximum limit dialogVisible: false, //View the image pop-up box imgUrl: [], //Collection of addresses after uploading the image};
  },
  //Listen to the array of uploaded pictures (to handle the automatic rendering problem and the disappearance of the upload button when modifying);
  watch:
    fileList(newName, oldName) {
      if (newName.length == this.limit) this.showUpload = true;
      else this.showUpload = false;
    },
  },
  methods: {
    //Function for removing files from the file list handleRemove(file, fileList) {
      const index = this.fileList.findIndex((item) => item === file.uid);
      this.imgUrl.splice(index, 1);
      this.$emit("delUrl", this.imgUrl);
      if (fileList.length < this.limit) this.showUpload = false;
    },
    //Function when clicking an uploaded file in the file list handlePictureCardPreview(file) {
      this.imgUrl.url = file.url;
      this.dialogVisible = true;
    },
    //This is a method for uploading via a button instead of directly uploading submitUpload() {
      this.$refs.upload.submit();
    },
    //Function when file status changes (main logic function)
    uploadFile(e, fileList) {
      //Judge the maximum number of user uploads to make the upload button disappear if (fileList.length >= this.limit) this.showUpload = true;
      // const file = e.file; <- here it is not necessary to upload directly but upload through the button const file = e.raw; // <- here it is uploaded directly // size const size = file.size / 1024 / 1024 / 2;
      if (
        !(
          file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg"
        )
      ) {
        this.$notify.warning({
          title: "Warning",
          message:
            "Please upload images in the formats of image/png, image/gif, image/jpg, image/jpeg",
        });
      } else if (size > 2) {
        this.$notify.warning({
          title: "Warning",
          message: "Image size must be less than 2M",
        });
      } else {
        if (this.limit == 1) this.imgUrl = []; //When judging it as one, the array needs to be cleared const params = new FormData();
        params.append("source", file);
        uploadImg(params).then((res) => {
        //The data structure returned here (modify according to your own return structure)
          if (res.data.status === 1) {
            this.$message.success("Upload successful");
            this.imgUrl = res.data;
            //Call the parent component method to pass the image parameter this.$emit("getUrl", this.imgUrl);
          } else this.$message.error("Upload failed");
        });
      }
    },
    //Function when the number of files exceeds the limit handleExceed(files, fileList) {
      this.$message.info(`Only ${this.limit} pictures can be uploaded`);
    },
  },
};
</script>

//Modify the styles before and after uploading here (I think el-upload is not good-looking and you can modify it yourself)
<style scope>
.hide .el-upload--picture-card {
  display: none !important;
}
.avatar-uploader > .el-upload {
  width: 200px;
  height: 200px;
  line-height: 200px;
  border-radius: 0px;
  background: #fff;
  border: 1px dashed #ccc;
}
.avatar-uploader > .el-upload > i {
  font-size: 28px;
  color: #ccc;
}
.avatar-uploader > .el-upload-list {
  display: block;
}
.avatar-uploader > .el-upload-list > .el-upload-list__item {
  width: 200px;
  height: 200px;
  display: block;
}
.avatar-uploader > .el-upload-list > .el-upload-list__item > img {
  width: 200px;
  height: 200px;
  border-radius: 0px;
}
</style>

Use in the page - (Because I use it a lot here, I will write the global one. You can decide according to your own project)

main.js

//Image upload component import UploadImg from "@/views/common/UploadImg.vue";
Vue.component('UploadImg', UploadImg)

demo.vue

<el-form-item label="Upload picture">
 //limit the maximum number of images to upload //fileList image array //getUrl get the uploaded address //delUrl delete the uploaded address // disabled disable processing <UploadImg :limit="1" :file-list="fileList" @getUrl="getUrl($event,'Parameters you need to carry')" @delUrl="delUrl($event,'Parameters you need to carry')" :disabled="true" />
</el-form-item>

//Variable declaration data:{
 fileList:[]
 }
//Function getUrl(getUrl){
 console.log(getUrl)
 };
delUrl(getUrl){
console.log(getUrl)
};

Hope this article can help you!!

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue implements file upload function
  • Three ways to upload pictures using Vue
  • Submit form data in Vue axios (including uploading files)
  • The Uploader of Vue+Vant on the mobile terminal realizes the functions of uploading, compressing and rotating pictures
  • Vue+elementUI implements form and image upload and verification function example
  • vue+elementUI realizes the picture upload function
  • Use input[type="file"] in vue to implement file upload function
  • Detailed explanation of Vue calling mobile phone camera and photo album and uploading
  • Vue upload component vue Simple Uploader usage example
  • Two ways to implement Excel file upload and download functions in Vue

<<:  Detailed explanation of how to use zabbix to monitor oracle database

>>:  Application of Beautiful Style Sheets in XHTML+CSS Web Page Creation

Recommend

6 Ways to Elegantly Handle Objects in JavaScript

Table of contents Preface 1. Object.freeze() 2. O...

Example of pre-rendering method for Vue single page application

Table of contents Preface vue-cli 2.0 version vue...

MySQL data archiving tool mysql_archiver detailed explanation

Table of contents I. Overview 2. pt-archiver main...

Understand the basics of Navicat for MySQL in one article

Table of contents 1. Database Operation 2. Data T...

A brief discussion on the efficiency of MySQL subquery union and in

Recent product testing found a problem that when ...

Vue uses WebSocket to simulate the chat function

The effect shows that two browsers simulate each ...

How to use Maxwell to synchronize MySQL data in real time

Table of contents About Maxwell Configuration and...

HTML implements read-only text box and cannot modify the content

Without further ado, I will post the code for you...

How CSS affects the white screen time during initial loading

Rendering pipeline with external css files In the...

How to configure Http, Https, WS, and WSS in Nginx

Written in front In today's Internet field, N...

Detailed explanation of MYSQL stored procedure comments

Table of contents 1. Instructions for use 2. Prep...

Implementation of MySQL master-slave status check

1. Check the synchronization status of A and B da...

Detailed explanation of js event delegation

1. Each function is an object and occupies memory...