封装 jpg/png/gif 转base64的方法
vue+element基础上进行的封装 小伙伴有需要直接带走就改改就好父元素<template><div><P @click="showUpLoad=true">点击我</P><upload :visible.sync="showUpLoad" @uploadImg="uploadImg" /></div></templ
·
vue+element基础上进行的封装 小伙伴有需要直接带走就改改就好
父元素
<template>
<div>
<P @click="showUpLoad=true">点击我</P>
<upload :visible.sync="showUpLoad" @uploadImg="uploadImg" />
</div>
</template>
<script>
import upload from '@/components/fitmentparam/upload.vue'
export default {
components:{upload},
data(){
return{
showUpLoad:false, //弹窗的显示与否
}
},
methods:{
// 获得base 64
uploadImg(base64){
console.log(base64)
}
}
}
</script>
子元素
<template>
<!-- 上传照片 -->
<el-dialog title="上传图片" v-bind="$attrs" width="40%" :modal-append-to-body="false" :close-on-click-modal="false" v-on="$listeners" >
<div>
<el-upload
action=""
:auto-upload="false"
:show-file-list="false"
:on-change="getFile"
:before-upload="beforeAvatarUpload"
class="upload"
>
<img v-if="imgSrc" :src="imgSrc" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
<el-row class="uploadButon">
<el-button type="primary" @click="submit">确定</el-button>
<el-button @click="close">取消</el-button>
</el-row>
</el-dialog>
</template>
<script>
export default {
data() {
return {
imgSrc: "", //保存图片的base64
};
},
created(){
this.search();
},
methods: {
getFile(file) {
this.getBase64(file.raw).then((res) => {
this.imgSrc=res;
//这里拿到base64的文件流,处理你自己的业务逻辑
});
},
beforeAvatarUpload() {},
getBase64(file) {
return new Promise(function (resolve, reject) {
let reader = new FileReader();
let imgResult = "";
reader.readAsDataURL(file);
reader.onload = function () {
imgResult = reader.result;
};
reader.onerror = function (error) {
reject(error);
};
reader.onloadend = function () {
resolve(imgResult);
};
});
},
submit(){
this.$emit('update:visible', false);
this.$emit('uploadImg', this.imgSrc); //子元素向父元素传 base64
this.imgSrc="";//制空 防止再次打开为上次保存的图片
},
close(){
this.$emit('update:visible', false);
}
},
};
</script>
<style lang="scss">
.upload{
text-align: center;
img{
width: 50%;
}
i{
width: 200px;
border: 1px solid #ddd;
text-align: center;
line-height: 200px;
border-radius: 20px;
}
}
.uploadButon{
margin: 20px auto;
text-align: center;
}
</style>
更多推荐
已为社区贡献4条内容
所有评论(0)