获取文件
<van-cell title="头像" is-link>
<van-image
class="avatar"
fit="cover"
round
:src="user.photo"
@click="$refs.inputRef.click()"
/>
</van-cell>
<input type="file" hidden ref="inputRef" @change="iptChange"/>
//ref获取input元素 change事件用于获取文件
iptChange(){
const file =this.$refs.inputRef.files[0]
//console.dir(file);
const imgUrl=URL.createObjectURL(file)
//console.log(imgUrl);
}
//这里URL是windows里的方法 所以前面不用加windows
使用ref获取组件的方法
1、父组件引入子组件,并在子组件中添加ref属性
<AddDept
ref="DialogDeprts"
:tree-node="node"
:show-dialog.sync="showDialog"
@getDeprts="getDepartments"
/>
2、子组件写方法
async getDetailDepartment() {
this.formData = await getDetailDepartment(this.treeNode.id)
},
3、父组件方法中通过ref引入子组件方法
this.$refs.DialogDeprts.getDetailDepartment(node.id)
头像裁剪
yarn add cropperjs
引入css和js
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
在mounted里写入代码
//获取元素
const image = this.$refs.img
//创建裁剪工具对象
//const cropper = new Cropper(image, {
// aspectRatio: 16 / 9,
// 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)
// }
//})
this.cropper = new Cropper(image, {
viewMode: 1, // 只能在裁剪的图片范围内移动
dragMode: 'move', // 画布和图片都可以移动
aspectRatio: 1, // 裁剪区默认正方形
autoCropArea: 1, // 自动调整裁剪图片
cropBoxMovable: false, // 禁止裁剪区移动
cropBoxResizable: false, // 禁止裁剪区缩放
background: false // 关闭默认背景
})
在方法里获取裁剪区域
this.cropper.getCroppedCanvas().toBlob(blob => {
console.log(blob)
})
设置api请求
传递数据
// 创建一个空formdata实例:用来传递文件数据
let fd = new FormData();
fd.append("photo", blob);
// 打印fd
// fd.forEach((v,k)=>{
// console.log(k,v);
// })
let res = await updateUserAvatar(fd);//请求
// console.log(res.data.data.photo);
this.$emit("close");
this.$emit("update:img", res.data.data.photo);