<template>
<div id="app">
<div>
<el-avatar
shape="square"
:size="120"
fit='cover'
:src="url"
></el-avatar>
</div>
<p @click='$refs.file.click()'>点击修改头像</p>
<el-dialog
title="编辑"
:visible.sync="centerDialogVisible"
width="30%"
@opened='onDialogOpened'
@closed='onDialogClosed'
center>
<div class="preview-image-wrap">
<!-- 把图片放到一个块原生里边 -->
<img class='preview-image' :src="previewImage" ref="preview-image" alt="">
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="centerDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="onUpdatePhoto">确 定</el-button>
</span>
</el-dialog>
<!-- multiple 是否可以多选文件 -->
<input type="file" ref="file" @change="onFileChange" hidden multiple>
<!--
地址:github.com/fengyuanchen/cropperjs 有步骤
cropperjs是基于纯原生js的库,可以在任何框架中使用.通用性更高
第一步: 安装 npm install cropperjs
第二步: 给img外包个块元素,然后设置img的样式
第三步: 引入包和css
第四步: 初始化裁切器
-->
</div>
</template>
<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
data() {
return {
url:'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
centerDialogVisible: false,
previewImage: '',
cropper: null,
};
},
methods: {
// 当前图片发生变化触发的事件
onFileChange() {
console.log('onFileChange');
//选择当前选中的第一张图片
const file = this.$refs.file?.files[0]
// 生成图片地址,可以直接设置给src
const blobData = window.URL.createObjectURL(file)
this.previewImage = blobData
console.log(blobData,file);
// 显示弹框
this.centerDialogVisible = true
//解决选择相同的图片不触发change事件
this.$refs.file.value = ''
},
// dialog完全打开后的回调
onDialogOpened() {
// 图片裁切其必须基于img进行初始化
// img必须是可见状态才能正常完成初始化
const image = this.$refs['preview-image']
// 第一次初始化好以后,如果预览裁切的图片发生了变化,裁切器默认不会更新
// 如果需要预览图片发生变化根新裁切器:
// 方法1: 裁切器.replace方法
// 方法2: 销毁裁切器, 重新初始化
if(this.cropper) {
//如果有图片存在就替换,并阻止代码往后执行
this.cropper.replace(this.previewImage)
return
}
this.cropper = new Cropper(image, {
aspectRatio: 1, // 3/2, 1,
viewMode: 1, //1不能移出.默认是0,可以移出
dragMode: 'none',
background: true,
// 移动裁切器会触发crop
// crop(event) {
// console.log(event.detail.x);
// console.log(event.detail.y);
// console.log(event.detail.width);
// console.log(event.detail.height);
// console.log(event.detail.rotate);
// console.log(event.detail.scaleX);
// console.log(event.detail.scaleY);
// }
})
},
// dialog完全关闭后的回调
onDialogClosed() {
// 销毁裁切器
// this.cropper.destroy()
},
onUpdatePhoto() {
// 获取裁切的图片对象
this.cropper.getCroppedCanvas().toBlob(file => {
console.log(file);
const fd = new FormData()
// fd.append('后端接口的字段名称',file)
fd.append('photo',file)
console.log(fd);
//把fd传给后端即可
})
this.centerDialogVisible = false
}
}
};
</script>
<style >
/* 设置样式 */
.preview-image{
display: block;
max-width: 100%;
height: 300px;
}
</style>