选择图片转base64格式组件简单封装-Base64ImageInpu
vue+ts中使用。
<!-- Base64ImageInput-base64格式的图片上传输入框,这里并不会真的将图片上传,只是将图片转为base64格式显示在输入框中并且让其可以预览 -->
<template>
<div>
<a-input class="w-full"
v-bind="$attrs"
v-on="$listeners"
@click="onClick"
v-model="state.inputVal"
readOnly>
<a-tooltip slot="suffix"
v-if="base64Img">
<div slot="title">
<img :src="base64Img"
class="w-14 h-14 my-4"
v-if="base64Img!=''">
</div>
<a-icon type="info-circle"
style="color: rgba(0,0,0,.45)" />
</a-tooltip>
</a-input>
<input type="file"
hidden="hidden"
ref="uploadButton"
:accept="acceptString"
@change="uploadImage()">
</div>
</template>
<script lang="ts">
import {
Component, Emit, Model, Watch, Prop, Vue
} from 'vue-property-decorator';
@Component({
name: 'GBase64ImageInput',
components: {
},
})
export default class GBase64ImageInput extends Vue{
@Model("change", {
default: () => ([]),
}) value!: any;
/**
* 文件类型(可以是字符串或者数组)
* 示例:
* accept="image/png"
* accept="image/*"
* accept="image/png,image/jpeg"
* :accept="['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']"
*/
@Prop({ type: [String, Array], default: () => ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'] })
accept!: string | string[];
get acceptString() {
if (Array.isArray(this.accept)) {
// 如果传的是 ['png','jpg'] 就转成 "image/png,image/jpeg"
return this.accept.map((ext) => {
if (ext.startsWith('image/')) return ext;
return `image/${ext}`;
}).join(',');
}
return this.accept;
}
base64Img = '';
state = {
inputVal: '',
}
onClick() {
(this.$refs.uploadButton as any).click();
}
uploadImage() {
const file = (this.$refs.uploadButton as any).files[0];
const reader = new FileReader();
let rawImg;
reader.onloadend = () => {
rawImg = reader.result;
this.base64Img = rawImg;
this.$set(this.state, 'inputVal', rawImg);
this.emitChange();
};
reader.readAsDataURL(file);
}
@Watch('value')
onValueChange(val: any) {
this.base64Img = val;
this.$set(this.state, 'inputVal', val);
}
@Emit("change")
emitChange() {
return this.base64Img;
}
mounted() {
if (_.size(this.value) > 0) {
this.base64Img = this.value;
this.$set(this.state, 'inputVal', this.value);
}
}
}
</script>
<style lang="less" scoped>
</style>
使用:
<template slot="thumbnail"
slot-scope="text, record">
<GBase64ImageInput v-model="modalState.record.thumbnail" />
</template>