概述
创建上传组件
主要思考使用组件间的双向绑定实现大量数据的上传并且将所有图片的id拼接成字符串返回,vue中的watch来监听上传变化,v-model绑定获取内容。这里实现的是图片的上传
1.uploadComponent.vue
<template id='example'>
<div>
<el-upload
:action="action"
:list-type="listType"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-progress="onProgress"
:on-success="uploadsuccess"
:file-list="fileLists"
accept="image/*"
:before-upload="beforeupload"
name="file"
:data="data"
:limit="limit"
:auto-upload="autoupload"
ref="upload"
multiple
:on-exceed="onExceed"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog
:visible.sync="dialogVisible"
width="60%"
center
title="图片预览"
top="5vh"
class="dialog"
>
<div class="p_block">
<img width="100%" :src="dialogImageUrl" alt />
</div>
</el-dialog>
</div>
</template>
<script>
export default {
props: {
data: Object, //上传接口接受的data
limit: {
type: Number,
default: 0
},/*上传文件的个数*/
fileList: Array,//文件数组
ids: String,//图片上传后返回id拼接字符串
action: String,
listType: {
type: String,
default: "picture-card"
},
onRemove: { type: Function, default: function() {} },
onSuccess: { type: Function, default: function() {} }
},
//监听image的变化,图片id
watch: {
images: {
handler(newName, oldName) {
this.$emit("input", newName);
//传值给父组件, 让父组件监听到这个变化
},
immediate: true // 代表在wacth里声明了firstName这个属性之后立即先去执行handler方法
}
},
data() {
return {
dialogImageUrl: "",
dialogVisible: false,
autoupload: true,
images: "",
fileLists: this.fileList
};
},
mounted() {
this.images = this.ids;
},
methods: {
beforeupload(file) {},
uploadsuccess(res, file, fileList) {
if (res.code == 1) {
let data = res.data;
this.images += data.id + ",";
} else {
this.$message.error(res.msg + "上传失败请稍后重试!");
}
},
onProgress: function(event, file, fileList) {},
onExceed: function(files, fileList) {
this.$message.error("只能上传" + this.limit + "个文件!");
},
handleRemove(file, fileList, op) {
let imgs = this.images.split(",");
let del_id;
if (file.id) {
del_id = file.id;
} else {
del_id = parseInt(file.response.data.id);
}
imgs.forEach((e, k) => {
if (e == del_id) {
imgs.splice(k, 1);
}
});
this.images = imgs.join(",");
if (op == 1) {
fileList.forEach((item, key) => {
if (item.response.data.id == file.response.data.id) {
fileList.splice(key, 1);
}
});
this.fileLists = fileList;
}
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
}
}
};
</script>
2.调用
<UploadCOM
:action="这里是上传的接口"
:data="接口需要的data"
:file-list="letter_intentFile"
list-type="picture-card"
//双向绑定返回上传图片的id
v-model="images"
//渲染时将id传回去
:ids="images"
></UploadCOM>
最后
以上就是耍酷小甜瓜为你收集整理的基于vue element 封装上传组件upload的全部内容,希望文章能够帮你解决基于vue element 封装上传组件upload所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复