ElementUi文件上传组件、查看图片组件封装及运用

一、文件上传组件
Upload.vue
<template>
  <el-upload
      drag
      action="#"
      list-type="picture-card"
      multiple
      :limit="1"
      :on-change="handleUpload"
      :class="{disabled:uploadDisabled}"
      :file-list="fileListCopy.data"
      :http-request="upload">
    <span class="el-upload__text">
      <em>点击<el-icon><Plus /></el-icon>上传</em>
      <br>或拖拽至此
    </span>
    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePreview(file)">
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)">
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref,reactive,getCurrentInstance,toRefs } from 'vue'
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'

//请求axios
const currentInstance = getCurrentInstance();
const { $axios } = currentInstance.appContext.config.globalProperties;
const { proxy } = currentInstance;
const uploadDisabled = ref(false)
const fileListCopy = reactive({
  data: []
});
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
//移除
const handleRemove = (file,fileList) => {
  console.log(file)
  fileListCopy.data = fileListCopy.data.filter(v => v.uid !== file.uid);
  uploadDisabled.value = false;
}
//查看
const handlePreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
//点击上传
const handleUpload = (file,fileList) =>{
  console.log(fileList.length)
  if(fileList.length>=1){
    uploadDisabled.value = true;
  }
}

//父组件文件标识
const props = defineProps({
  uploadFlag: String,
})
const {uploadFlag} =toRefs(props)
const emit = defineEmits(['callBack'])
const upload = (file)=>{
  let formData = new FormData();
  formData.append('uploadFile', file.file);
  $axios.post(
      "upload/file", 
       formData
  ).then((res)=>{
    //上传结果回调
    emit('callBack', {flag:uploadFlag.value,url:res.data})
  }).catch(err=>{
    proxy.$message.error(err.message)
  })
}
</script>
<style>
.disabled .el-upload--picture-card {
  display: none!important;
}
 img{ width: 100%; }
</style>

二、图片查看组件
ViewPhoto.vue:
<template>
  <el-dialog v-model="dialogVisible" :title="viewTitle">
    <img w-full :src="dialogImageUrl" alt="Preview Image" @error="getErrorImage($event)"/>
  </el-dialog>
</template>
<script setup>
import defaultImage from "@/components/files/errorImage.png"
import {getCurrentInstance, toRefs,ref,onMounted} from "vue";
import { ElMessage } from "element-plus";
const currentInstance = getCurrentInstance();
const { $axios } = currentInstance.appContext.config.globalProperties;

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const viewTitle = ref("")
//父组件获取url
const props = defineProps({
  url: String,
  title:String
})
const {url,title} =toRefs(props)
//获取图片的完整地址
const getPreviewUrl = () => {
  $axios.get(
      "photo/preview",{fileName:url.value}
  ).then((res)=>{
    viewTitle.value = title.value
    dialogImageUrl.value = res.data
    dialogVisible.value = true
  }).catch(err=>{
    if(err.message == undefined){
      ElMessage.error("获取文件阅览地址异常,请联系管理员")
    }
    ElMessage.error(err.message)
  })
}
onMounted(()=>{
  getPreviewUrl();
})
//异常处理
const getErrorImage = (e)=>{
  e.target.src = defaultImage
}
</script>
<style scoped>
img{
  width: 100%;
  height: 100%;
}
</style>
三、组件运用
<template>
  <el-row>
    <div style="width:100%" class="fileup"  size="large">上传照片</div>
    <el-form-item style="margin-top: 10px;" v-model="userInfo.header" label="头像" size="large">
      <!--文件上传组件-->
      <uc-upload-file :uploadFlag="headPicture" @callBack="getUploadRes"></uc-upload-file>
    </el-form-item>
    <!--文件查看,异步加载文件查看组件-->
    <el-form-item label="头像" @click="viewPhoto(userDetailInfo.avatar,'查看头像')" size="large">
      <el-input  v-model="userInfo.avatar" :disabled='true' title="点击查看" size="large" />
    </el-form-item>
  </el-row>
</template>
<script  setup>
import {ref} from 'vue';
import { ElMessage } from "element-plus";
//上传图片
//标识:hp-头像
const headPicture = ref("hp")
//上传结果
const getUploadRes = (res) => {
  if(res.flag == headPicture.value){
    userInfo.header = res.url
    return;
  }
  userInfo.image = res.url
}
//查看图片
const photoUrl = ref("")
const viewTitle = ref("")
const viewPhotoComponent = shallowRef(null);
const viewPhoto = (url,title)=>{
  if(url == undefined){
    ElMessage.warning("请先上传"+title)
    return
  }
  photoUrl.value = url
  viewTitle.value = title
  //异步加载查看图片组件
  viewPhotoComponent.value = defineAsyncComponent(
      () => import("@/components/files/ViewPhoto.vue")
  );
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
封装 Element UI 的上传组件,你可以创建一个自定义的 Vue 组件,然后在其中使用 Element UI 的 el-upload 组件。以下是一个简单的封装示例: ```vue <template> <div> <el-upload ref="upload" :action="uploadUrl" :on-success="handleSuccess" :before-upload="beforeUpload" :auto-upload="autoUpload" > <slot></slot> </el-upload> </div> </template> <script> export default { name: 'CustomUpload', props: { uploadUrl: { type: String, required: true }, autoUpload: { type: Boolean, default: true } }, methods: { handleSuccess(response, file, fileList) { // 处理上传成功的回调逻辑 this.$emit('upload-success', response, file, fileList); }, beforeUpload(file) { // 可以在这里添加一些上传前的逻辑判断,如文件类型、大小等 return true; // 返回 true 表示允许上传 }, clearFiles() { this.$refs.upload.clearFiles(); }, abortUpload() { this.$refs.upload.abort(); } } }; </script> ``` 在这个示例中,我们创建了一个 `CustomUpload` 组件,它接受一个 `uploadUrl` 属性来指定上传地址,并且还有一个可选的 `autoUpload` 属性来控制是否自动上传。 你可以在组件中添加自定义的逻辑和样式,并使用 `this.$refs.upload` 来访问 Element UI 的上传组件实例,从而调用其方法和获取上传的文件信息。 使用示例: ```vue <template> <div> <custom-upload upload-url="上传地址" :auto-upload="false" @upload-success="handleUploadSuccess" > <el-button size="small" type="primary">点击上传</el-button> </custom-upload> </div> </template> <script> import CustomUpload from '@/components/CustomUpload.vue'; export default { components: { CustomUpload }, methods: { handleUploadSuccess(response, file, fileList) { console.log('上传成功'); } } }; </script> ``` 在上面的示例中,我们在 `CustomUpload` 组件中使用了一个插槽,用来插入自定义的上传按钮。当文件上传成功后,会触发 `upload-success` 事件,你可以在父组件中监听该事件并处理相应的逻辑。 这样,你就可以通过封装 Element UI 的上传组件来方便地在项目中使用了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值