vue3 ElementPlus el-upload 图片列表缩略图模式添加查看大图 删除等自定义按钮
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue 3和Element Plus中,可以通过自定义el-upload的列表项模板来实现自定义按钮和图片的查看、删除功能。以下是一个简化的例子:
<template>
  <el-upload
    list-type="picture-card"
    action="https://jsonplaceholder.typicode.com/posts/"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
  >
    <template #default="{ file }">
      <div class="image-container">
        <img :src="file.url" alt="" class="image-item"/>
        <span class="delete-button" @click="handleRemove(file)">X</span>
      </div>
      <div class="el-upload__text">上传照片</div>
    </template>
  </el-upload>
  <el-dialog :visible.sync="dialogVisible">
    <img :src="dialogImageUrl" alt="" style="display: block; max-width: 100%;" />
  </el-dialog>
</template>
 
<script setup>
import { ref } from 'vue';
import { ElUpload, ElDialog } from 'element-plus';
 
const fileList = ref([
  { name: 'food.jpg', url: 'http://placekitten.com/300/300' },
  // ...可以添加更多文件对象
]);
 
const dialogVisible = ref(false);
const dialogImageUrl = ref('');
 
const handlePreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
 
const handleRemove = (file) => {
  // 实现删除逻辑,例如从fileList中移除对应文件
  const index = fileList.value.indexOf(file);
  if (index !== -1) {
    fileList.value.splice(index, 1);
  }
};
</script>
 
<style scoped>
.image-container {
  position: relative;
  display: inline-block;
}
.image-item {
  width: 100px;
  height: 100px;
  object-fit: cover;
}
.delete-button {
  position: absolute;
  top: 0;
  right: 0;
  background-color: red;
  color: white;
  padding: 2px 5px;
  border-radius: 50%;
  cursor: pointer;
}
</style>在这个例子中,我们使用el-upload组件的list-type属性设置为picture-card来展示缩略图,并通过template #default定义了自定义的列表项结构。在这个结构中,我们添加了一个图片和一个用于删除的按钮。点击图片会弹出查看大图的对话框,点击删除按钮会触发删除操作。
注意:这个例子中的删除操作只是简单地从fileList数组中移除文件对象,并没有进行真实的文件删除操作。在实际应用中,你需要根据后端API来实现删除文件的逻辑。
评论已关闭