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

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

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

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

pictureupload.vue:

<template> <div> <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" :on-success="upLoadSuccess" :data="upLoadData" :headers="headers" :limit="limit"> <i></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img :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); },

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/a8f1a014c704a1b91ff22c23519c1e70.html