在一个vue项目中,封装一个拍照的组件
仅适用于浏览器,App打包后安卓手机不满足
组件实现拍照功能,样式可以自己设置
getPhoto.vue
<template>
<div class="getPhone">
<input accept="image/*" type="file" @change="acceptImage"/>
<van-popup v-model="showload" :close-on-click-overlay="false">
<van-loading class="loadimg" type="spinner" ></van-loading>
</van-popup>
</div>
</template>
<script>
import { Dialog } from 'vant';
export default {
name:"getPhoto",
props:["index2"],
data(){
return{
showload:false
};
},
methods:{
acceptImage(){
let file = event.target.files[0];
if(file.size >= 6291456) {
// console.log("超过6MB数据大小,请重新选择上传");
Dialog.alert({
title: '提示',
message: '超过6MB数据大小,请重新选择上传'
}).then(() => {
// on close
});
}else{
this.showload = true;
let form = new FormData();
form.append('file',file,file.name);
this.$axios.post("请求地址",form,{
headers:{'Content-Type':'multipart/form-data'}
}).then(response => {
this.showload = false;
// console.log(response.data)
let data = {
url:response.data.url,
index:this.index2 //用index来区分是哪个模块调用的,进而去做不同的操作
};
this.$emit("imgsrc",data);
}).catch(error => {
Dialog.alert({
title: '提示',
message: '上传失败'
}).then(() => {
// on close
});
})
}
}
}
}
</script>
<style scoped>
.getPhone{
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
input{
width: 100%;
height: 100%;
position: absolute;
opacity: 0;
z-index: 999;
top: 0;
left: 0;
}
.loadimg{
padding: 10px;
border-radius: 5px;
}
</style>
在需要调用的页面引入
import getPhoto from '@/components/common/getPhoto';
components:{
getPhoto
},
html 里面的写法:
<div class="getphotos">
< img :src="path+img3" class="img1" v-if="img3">
< img src="../../assets/img/Authentication/1_07.png" class="img1" v-if="!img3">
<get-photo @imgsrc="showdata"></get-photo>
</div>
js:
//展示刚刚上传的图片
showdata(data){
this.imageurl = data.url;
this.whichImg=data.index;
let type = typeof(this.imageurl);
this.img3 = this.imageurl;
},
很久之前写的,并且写的也比较仓促,也许还是有不足的地方,不过基本可以符合要求