upload-image.vue 2.47 KB
<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>