upload-image.vue
2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<template>
<view class="upload-image">
<view class="image-list">
<view class="image-item" v-for="(item, index) in imageList" :key="index">
<image class="image" :src="item.url || item" mode="aspectFill"></image>
<view class="delete-btn" @click="deleteImage(index)">
<u-icon name="close" color="#fff"></u-icon>
</view>
</view>
<view class="upload-btn" v-if="imageList.length < maxCount" @click="chooseImage">
<u-icon name="plus" size="40" color="#999"></u-icon>
<view class="upload-text">上传图片</view>
</view>
</view>
<view class="tips" v-if="tips">{{ tips }}</view>
</view>
</template>
<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue';
import { chooseAndUploadImages } from '@/common/utils/upload';
const props = defineProps({
maxCount: { type: Number, default: 9 },
modelValue: { type: Array, default: () => [] },
tips: { type: String, default: '最多上传9张图片' },
showTips: { type: Boolean, default: true }
});
const emit = defineEmits(['update:modelValue', 'change']);
const imageList = ref([...props.modelValue]);
watch(() => props.modelValue, (newVal) => imageList.value = [...newVal], { deep: true });
const chooseImage = async () => {
try {
const res = await chooseAndUploadImages({ count: props.maxCount - imageList.value.length });
imageList.value = [...imageList.value, ...res];
emit('update:modelValue', imageList.value);
emit('change', imageList.value);
} catch (err) {
console.error('上传失败:', err);
}
};
const deleteImage = (index) => {
imageList.value.splice(index, 1);
emit('update:modelValue', imageList.value);
emit('change', imageList.value);
};
</script>
<style scoped>
.upload-image { width: 100%; }
.image-list { display: flex; flex-wrap: wrap; gap: 10rpx; }
.image-item { position: relative; width: 200rpx; height: 200rpx; border-radius: 8rpx; overflow: hidden; }
.image { width: 100%; height: 100%; }
.delete-btn { position: absolute; top: 0; right: 0; width: 40rpx; height: 40rpx; background: rgba(0,0,0,0.5); border-radius: 50%; display: flex; align-items: center; justify-content: center; }
.upload-btn { width: 200rpx; height: 200rpx; border: 1rpx dashed #ddd; border-radius: 8rpx; display: flex; flex-direction: column; align-items: center; justify-content: center; background: #f9f9f9; }
.upload-text { font-size: 24rpx; color: #999; margin-top: 10rpx; }
.tips { font-size: 24rpx; color: #999; margin-top: 10rpx; }
</style>