vue-cli结合Element-ui基于cropper.js封装vue实现图片裁剪组件功能

2020-06-16 05:59:27易采站长站整理

files = this.$avatarInput.prop('files');
if (files.length > 0) {
file = files[0];
if (this.isImageFile(file)) {
if (this.url) {
URL.revokeObjectURL(this.url); // Revoke the old one
}
this.url = URL.createObjectURL(file);
this.startCropper();
}
}
} else {
file = this.$avatarInput.val();
if (this.isImageFile(file)) {
this.syncUpload();
}
}
},
//裁剪提交
submit: function () {
if (!this.$avatarSrc.val() && !this.$avatarInput.val()) {
return false;
}
if (this.support.formData) {
this.ajaxUpload();
return false;
}
}, //旋转事件
rotate: function (e) {
var data;
if (this.active) {
data = $(e.target).data();
if (data.method) {
this.$img.cropper(data.method, data.option);
}
}
},
isImageFile: function (file) {
if (file.type) {
return /^image/w+$/.test(file.type);
} else {
return /.(jpg|jpeg|png|gif)$/.test(file);
}
},
startCropper: function () {
var _this = this;
if (this.active) {
this.$img.cropper('replace', this.url);
} else {
this.$img = $('<img src="'%20+%20this.url%20+%20'">');
this.$avatarWrapper.empty().html(this.$img);
this.$img.cropper({
viewMode:1,
aspectRatio: 1,
preview: this.$avatarPreview,
restore:false,
crop: function (e) {
var json = [
'{"x":' + e.x,
'"y":' + e.y,
'"height":' + e.height,
'"width":' + e.width,
'"rotate":' + e.rotate + '}'
].join();
//裁图参数存起来
_this.$avatarData.val(json);
}
});
this.active = true;
}
},
stopCropper: function () {
if (this.active) {
this.$img.cropper('destroy');
this.$img.remove();
this.active = false;
}
},
ajaxUpload: function () {
var url = '/oss/file/cropping';
var data = new FormData(this.$avatarForm[0]);
var _this = this;
$.ajax(url, {
type: 'post',
data: data,
dataType: 'json',
processData: false,
contentType: false,
success: function (data,textStatus) {
_this.submitDone(data);
if(data.success){
//将返回的数据传给父组件
_this.$emit('cropper-success',data.data);
_this.cropDone();
}
},
});
},
syncUpload: function () {
this.$avatarSave.click();
},
submitDone: function (data) {
if ($.isPlainObject(data) && data.state === 200) {
if (data.result) {
this.url = data.result;
if (this.support.datauri || this.uploaded) {
this.uploaded = false;
this.cropDone();
} else {
this.uploaded = true;