亲宝软件园·资讯

展开

Vue开发之封装上传文件组件与用法示例

人气:0

本文实例讲述了Vue开发之封装上传文件组件与用法。分享给大家供大家参考,具体如下:

使用elementui的 el-upload插件实现图片上传组件

每个项目存在一定的特殊性,所以数据的处理会不同

pictureupload.vue:

<template>
  <div class="pictureupload">
    <el-upload
        :action="baseUrl + '/api/public/image'"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :on-exceed="handleExceed"
        :before-remove="beforeRemove"
        name="img"
        :on-success="upLoadSuccess"
        :data="upLoadData"
        :headers="headers"
        :limit="limit">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import store from "@/store";
export default {
  props: {
    imgList: {
      type: Array,
      default: []
    }, // 父组件传递的图片列表
    limit: "" // 图片数量限制
  },
  data() {
    return {
      fileList: [],
      upLoadData: {
        img: ""
      },
      baseUrl: process.env.BASE_API,
      dialogVisible: false,
      dialogImageUrl: "",
      headers: {
        Authorization: store.getters.token_type + " " + store.getters.token
      } // 接口调用token
    };
  },
  watch: {
    // 监听imgList的变化: fileList要求的格式为[{url: img}],所以监听imgList变化后将其进行处理,赋值给fileList
    imgList: {
      handler(newValue, oldValue) {
        if(newValue.length === 0) {
          this.fileList = [];
          return;
        }
        for (let i = 0; i < newValue.length; i++) {
          if (oldValue[i] != newValue[i]) {
            this.fileList = [];
            newValue.forEach(el => {
              this.fileList.push({url: el})
            })
            return;
          }
        }
      },
      deep: true
    }
  },
  methods: {
    // 图片移除时处理数据
    handleRemove(file, fileList) {
      let item = [];
      fileList.forEach(el => {
        item.push(el.url);
      });
      this.$emit("removeimg", item);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 判断图片数量
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ${this.limit} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {},
    // 上传图片成功事件
    upLoadSuccess(response) {
      this.$emit("uploadimg", response.message);
      this.$message("上传成功",);
    }
  },
  mounted() {
    if (this.imgList.length != 0) {
      this.imgList.forEach(el => {
        this.fileList.push({ url: el });
      });
    }
  }
};
</script>

使用上传图片组件:

<pictureupload @uploadimg="uploadimg" :imgList="ruleForm.img" :limit="3" @removeimg="removeimg"></pictureupload>

removeimg(item) {
  this.ruleForm.img = item;
},
uploadimg(item) {
  this.ruleForm.img.push(item);
},

希望本文所述对大家vue.js程序设计有所帮助。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论