首先说一下要实现的功能,封装一个上传图片的子组件,子组件上传的图片会被父组件接收并且同时随着父组件的其他信息一起上传到服务器中,实现编辑和添加的功能。
首先将子组件的上传功能完成
<template>
<div>
<el-upload
class="avatar-uploader"
:action="action"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="photo" :src="photo" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<el-button type="text" @click="removeImage" style="color: red">删除</el-button>
</div>
</template>
<script>
export default {
name: "Upload",
data(){
return{
action:'图片上传地址(需自己填写)',
}
},
methods:{
handleAvatarSuccess(res) {
this.photo = res.url;
},
removeImage(){
this.photo = ''
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!');
return
}
return isJPG && isLt2M;
},
}
}
</script>
这里只是完成了子组件的上传和显示功能,与父组件没有任何联系。
如果想要完成真正的上传,就需要图片文件的来回传递,如果编辑时想要展示父组件的内容,就需要从父组件传递图片进行展示,如果子组件向父组件传递上传的图片也需要组件间传值。
父传子用的是props,但是props会出现一个问题,它传给子组件的值是最初始的数据,并不是服务器传给我们的数据,因为收到服务器数据在props传值之后,这时候就需要对子组件进行判断,当没有这个值时不传递。
<Upload @newImage='getNewImage' :value="form.license" v-if="form.license !== null"></Upload>
拿到父组件的值之后需要在子组件展示
props:['value'],
created() {
this.change()
},
methods:{
change(){
this.photo = this.value;
},
handleAvatarSuccess(res) {
this.photo = res.url;
this.sendMessage.imgUrl = res.url
this.$emit("newImage", this.sendMessage);
},
此时子组件的值并不灵活,会影响到添加和编辑的展示,所以此时的photo改为计算属性。
computed:{
photo(){
return this.value
}
},
接下来就要需要子组件给父组件传值,用的是自定义事件
handleAvatarSuccess(res) {
this.photo = res.url;
this.sendMessage.imgUrl = res.url
this.sendMessage.imgName = this.imgName
this.$emit("newImage", this.sendMessage);
},
removeImage(){
this.photo = ''
this.sendMessage.imgUrl = ''
this.sendMessage.imgName = this.imgName
this.$emit("newImage", this.sendMessage);
},
父组件接收,为了分辨上传的数据,所以父组件向子组件再传递一个字段名imgName,然后使用for in 对form的值进行判断,然后赋值。
<Upload @newImage='getNewImage' :value="form.license" imgName="license" v-if="form.license !== null"></Upload>
getNewImage(e){
for(let key in this.form){
if (key == e.imgName){
this.form[key] = e.imgUrl
}
}
},
封装的并不是很好,欢迎大佬们提出建议。