<template>
<a-upload
v-model:file-list="fileList"
name="file"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
:action="action"
:before-upload="beforeUpload"
@change="handleChange"
v-bind="$attrs"
>
<a-image
:width="48"
:height="48"
v-if="value" :src="value"
/>
<div v-else>
<loading-outlined v-if="loading"></loading-outlined>
<plus-outlined v-else></plus-outlined>
</div>
</a-upload>
</template>
<script>
import { defineComponent, ref, watch } from 'vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
export default defineComponent({
components: {
LoadingOutlined,
PlusOutlined,
},
props:['value'],
inheritAttrs: false,
emits:['update:value'],
setup(props,{emit}) {
const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref();
const action = ref(`http://192.168.2.2:8080/uplaodurl`);
const handleChange = info => {
if (info.file.status === 'uploading') {
loading.value = true;
return;
}
if (info.file.status === 'done') {
loading.value = false;
if(info.file.response.code==0){
emit('change',info)
imageUrl.value = info.file.response.data;
}
}
if (info.file.status === 'error') {
loading.value = false;
message.error('upload error');
}
};
const beforeUpload = file => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
}
return isJpgOrPng && isLt2M;
};
watch(imageUrl, (newValue, oldValue) => {
emit('update:value', newValue)
});
return {
fileList,
loading,
imageUrl,
action,
handleChange,
beforeUpload,
};
},
});
</script>
<style>
.avatar-uploader > .ant-upload {
width: 64px;
height: 64px;
}
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
margin-top: 8px;
color: #666;
}
</style>
vue3 ant-vue form表单里的upload组件封装
最新推荐文章于 2024-05-14 10:09:41 发布