在父组件
注意父传子的头像值 @update-pic="userprofile.photo = $event"
<!-- /导航栏 -->
<van-cell title="头像" is-link @click="$refs.inputFile.click()">
<input type="file" hidden ref="inputFile" @change="inputonChange" />
<van-image class="avatar" fit="cover" round :src="userprofile.photo" />
</van-cell>
<!-- 头像-->
<van-popup v-model="isShowPopPic" position="bottom" :style="{ height: '100%' }">
<edit-user-pic
v-if="isShowPopPic"
@close="isShowPopPic = false"
:img="img"
@update-pic="userprofile.photo = $event"
/>
</van-popup>
data() {
return {
userprofile: {},
isShowPopName: false,
isShowPopSex: false,
isShowPopbirthday: false,
isShowPopPic: false,
img: '',
};
},
inputonChange() {
// console.log(this.$refs.inputFile.files[0]);
const file = this.$refs.inputFile.files[0];
this.img = window.URL.createObjectURL(file);
this.isShowPopPic = true;
this.$refs.inputFile.value = '';
},
在子组件里面
<template>
<div class="edit-user-pic">
<img :src="img" ref="img" />
<div class="editBtn">
<span @click="$emit('close')">取消</span>
<span @click="confirm">完成</span>
</div>
</div>
</template>
<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import { editPhotoAjax } from '@/api/user';
import asyncErrorHandler from '@/utils/asyncErrorHandler';
export default {
name: 'editUserPic',
props: {
img: {
type: [String, Object],
required: true,
},
},
methods: {
confirm() {
this.$toast.loading({
message: '保存中...',
forbidClick: true,
loadingType: 'spinner',
duration: 0,
});
this.cropper.getCroppedCanvas().toBlob(async (blob) => {
const formData = new FormData();
formData.append('photo', blob);
const [err, res] = await asyncErrorHandler(editPhotoAjax(formData));
console.log(res);
if (err) return this.$toast.fail('头像更新失败');
this.$toast.success('头像更新成功');
this.$emit('close');
this.$emit('update-pic', res.data.photo);
});
},
},
mounted() {
const image = this.$refs.img;
this.cropper = new Cropper(image, {
aspectRatio: 16 / 9,
viewMode: 1, // 只能在裁剪的图片范围内移动
dragMode: 'move', // 画布和图片都可以移动
autoCropArea: 1, // 自动调整裁剪图片
cropBoxMovable: false, // 禁止裁剪区移动
cropBoxResizable: false, // 禁止裁剪区缩放
background: false, // 关闭默认背景
});
console.log(this.cropper);
},
};
</script>
<style lang="less" scoped>
.edit-user-pic {
background-color: #333;
height: 100%;
.editBtn {
position: absolute;
bottom: 0;
color: #fff;
display: flex;
width: 100%;
justify-content: space-between;
align-items: center;
font-size: 60px;
}
}
</style>