调用
<template>
<div>
...
<ImpCropper
ref="imgcropper"
@cancel="cropperCancel"
@finish="cropperFinish"
></ImpCropper>
...
</div>
</template>
<script>
import ImpCropper from "@/components/images/cropper/index.vue";
export default {
components: { ImpCropper },
methods:{
fn(file){
this.$refs.imgcropper.init(file.file);
},
cropperCancel(){
},
cropperFinish(file) {
console.log(file)
},
}
}
</script>
组件
<template>
<div>
<el-dialog
@opened="onDialogOpened"
@closed="onDialogClosed"
:append-to-body="true"
:close-on-click-modal="false"
title="修改头像"
:visible.sync="imgCropperShow"
>
<div class="preview-image-wrap">
<img
ref="preview-image"
class="preview-image"
:src="previewImage"
alt=""
/>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="onDialogClosed">取 消</el-button>
<el-button
type="primary"
@click="onUpdatePhoto"
:loading="updatePhotoLoading"
>确 定</el-button
>
</span>
</el-dialog>
</div>
</template>
<script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
export default {
data() {
return {
imgCropperShow: false,
updatePhotoLoading: false,
previewImage: "",
cropper: null,
};
},
methods: {
init(file) {
this.imgCropperShow = true;
this.previewImage = window.URL.createObjectURL(file);
},
onDialogOpened() {
const image = this.$refs["preview-image"];
if (this.cropper) {
this.cropper.replace(this.previewImage);
}
const cropper = new Cropper(image, {
aspectRatio: 1 / 1,
viewMode: 1,
dragMode: "none",
background: true,
cropBoxResizable: false,
});
this.cropper = cropper;
},
onDialogClosed() {
this.cropper.destroy();
this.cropper = null;
this.$emit("cancel");
this.imgCropperShow = false;
},
onUpdatePhoto() {
this.updatePhotoLoading = true;
this.cropper.getCroppedCanvas().toBlob((blob) => {
let type = "text/plain";
let file = new File([blob], "headimg.png", {
type,
lastModified: new Date().getTime(),
});
this.$emit("finish", { file });
this.imgCropperShow = false;
this.updatePhotoLoading = false;
});
},
},
};
</script>
<style lang="scss" scoped>
.preview-image-wrap {
.preview-image {
display: block;
max-width: 100%;
height: 200px;
}
}
</style>