91 lines
2.0 KiB
Vue
91 lines
2.0 KiB
Vue
<template>
|
|
<div>
|
|
<el-upload
|
|
class="avatar-uploader"
|
|
:action="state.path"
|
|
:show-file-list="false"
|
|
:on-success="handleSuccess"
|
|
:before-upload="beforeUpload"
|
|
>
|
|
<img v-if="state.imageUrl" :src="state.imageUrl" class="avatar" />
|
|
<el-icon v-else class="avatar-uploader-icon">
|
|
<Plus />
|
|
</el-icon>
|
|
</el-upload>
|
|
</div>
|
|
</template>
|
|
<script setup lang="ts">
|
|
const props = defineProps({
|
|
imageUrl: {
|
|
type: String,
|
|
default: '',
|
|
},
|
|
})
|
|
|
|
// 创建 emit 事件
|
|
import { UploadProps } from 'element-plus'
|
|
const emit = defineEmits();
|
|
const state = reactive({
|
|
imageUrl: '',
|
|
path:import.meta.env.VITE_API_FRONT_BASE_URL+"/api/upload"
|
|
})
|
|
// 监控 props.imageUrl 的变化
|
|
watch(
|
|
() => props.imageUrl, // 监听 imageUrl 的变化
|
|
(newVal, oldVal) => {
|
|
// console.log('imageUrl changed from', oldVal, 'to', newVal)
|
|
// 这里可以执行相应的操作,比如清空本地 state.imageUrl 或更新界面
|
|
state.imageUrl = newVal // 更新本地的 imageUrl
|
|
}
|
|
)
|
|
onMounted(()=>{
|
|
console.log(props.imageUrl)
|
|
if (props.imageUrl){
|
|
state.imageUrl = props.imageUrl
|
|
}
|
|
})
|
|
|
|
// 上传前的钩子,返回 false 可以阻止上传
|
|
function beforeUpload(file) {
|
|
const isImage = file.type.startsWith('image/')
|
|
if (!isImage) {
|
|
ElMessage.error('只能上传图片文件!')
|
|
}
|
|
return isImage
|
|
}
|
|
|
|
// 上传成功后的回调
|
|
const handleSuccess: UploadProps['onSuccess'] = (
|
|
response,
|
|
uploadFile
|
|
) => {
|
|
state.imageUrl = response.data.path
|
|
ElMessage.success('上传成功')
|
|
console.log("fanhui1",response)
|
|
// 通过 emit 将路径传递给父组件
|
|
emit('update:imageUrl', response.data.absolute);
|
|
}
|
|
</script>
|
|
|
|
<style scoped>
|
|
:deep(.el-upload ){
|
|
border: 1px dashed var(--el-border-color);
|
|
border-radius: 6px;
|
|
cursor: pointer;
|
|
position: relative;
|
|
overflow: hidden;
|
|
transition: var(--el-transition-duration-fast);
|
|
}
|
|
.el-icon.avatar-uploader-icon {
|
|
font-size: 28px;
|
|
color: #8c939d;
|
|
width: 178px;
|
|
height: 178px;
|
|
text-align: center;
|
|
}
|
|
.avatar{
|
|
width: 178px;
|
|
height: 178px;
|
|
}
|
|
</style>
|