原始图
父组件:
<div class="my-basic">
<my-basic :items="category[3].menu[0]"
@uploadHeadImg="uploadHeadImg"
@handleFile="handleFile"></my-basic>
</div>
父组件js:
import {uploadPicture} from "~/api/user"; 引用接口方法
export default {
methods: {
// 个人设置--基本信息 打开图片上传
uploadHeadImg() {
this.$el.querySelector(".hiddenInput").click();
},
// 将头像显示
handleFile(files) {
//单文件上传 不用上传图片接口
const reader = new FileReader();
reader.onload = data => {
let res = data.target
this.category[3].menu[0].userInfo.avatar = res.result
};
reader.readAsDataURL(files[0]);
// 多文件上传+接口
let uploadData = new FormData()
for (let i = 0; i < files.length; i++) {
let file = files[i]
if (file.size / (Math.pow(1024, 2)) > 2) {
this.$notify.error({
title: "错误",
message: "不能上传大小超过2MB的图片"
});
} else {
uploadData.append('file[]', file)
}
}
//调用接口
uploadPicture(uploadData).then(res => {
this.category[3].menu[0].userInfo.avatar = getPicture + res.data.data.picture_ids[res.data.data.picture_ids.length-1] //赋值 多张图片同时上传取最后一张
})
},
}
}
子组件
<div class="set-avatar">
<div class="avatar">
<img :src="items.userInfo.avatar" alt="">
</div>
<dl class="upload-avatar" @click.stop="$emit('uploadHeadImg')">
<dt>
<button>上传头像</button>
<input multiple type="file" accept="image/*" @change="handleFile" class="hiddenInput"/>
</dt>
<dd>支持JPG、PNG等格式图片大小不超过2M</dd>
</dl>
</div>
js:
export default {
props: ["items"],
methods: {
// 获取待上传文件
handleFile(e) {
let files = e.target.files;
this.$emit('handleFile', files)
},
}
};
scss样式
.set-avatar {
display: flex;
align-items: center;
padding-bottom: 40px;
border-bottom: 1px solid #dfe4e8;
.avatar {
margin-right: 34px;
img {
width: 70px;
height: 70px;
border-radius: 50%;
}
}
dl {
dt {
width: 60px;
height: 24px;
overflow: hidden;
button {
padding: 0 6px;
height: 24px;
background: #7888f2;
border-radius: 4px;
font-size: 12px;
color: #fff;
}
}
dd {
font-size: 12px;
color: #9194ab;
margin-top: 21px;
}
}
}
api文件夹下的user.js接口文件
// 上传图片
export const uploadPicture = data => {
return axios.request({
headers: {
'Content-Type': 'multipart/form-data'
},
url: 'picture',
data,
method: 'post'
})
}
完成后的效果图