当前位置:首页 > VUE

vue实现附件组件

2026-01-17 17:38:32VUE

Vue 实现附件组件的方法

基础组件结构

使用 Vue 的单文件组件(SFC)方式创建一个基础的附件上传组件。需要包含文件选择、预览、上传和删除功能。

<template>
  <div class="attachment-component">
    <input type="file" @change="handleFileChange" multiple />
    <div v-for="(file, index) in files" :key="index" class="file-item">
      <span>{{ file.name }}</span>
      <button @click="removeFile(index)">删除</button>
    </div>
    <button @click="uploadFiles">上传</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      files: []
    }
  },
  methods: {
    handleFileChange(event) {
      this.files = Array.from(event.target.files)
    },
    removeFile(index) {
      this.files.splice(index, 1)
    },
    uploadFiles() {
      // 上传逻辑
    }
  }
}
</script>

文件预览功能

对于图片类型的附件,可以添加预览功能。使用 URL.createObjectURL 生成临时链接显示预览。

<template>
  <div v-for="(file, index) in files" :key="index">
    <img v-if="file.type.startsWith('image/')" :src="getPreview(file)" width="100" />
    <span>{{ file.name }}</span>
  </div>
</template>

<script>
methods: {
  getPreview(file) {
    return URL.createObjectURL(file)
  },
  beforeDestroy() {
    this.files.forEach(file => {
      URL.revokeObjectURL(this.getPreview(file))
    })
  }
}
</script>

上传功能实现

使用 axios 或其他 HTTP 客户端实现文件上传功能。需要构建 FormData 对象发送文件数据。

methods: {
  async uploadFiles() {
    const formData = new FormData()
    this.files.forEach(file => {
      formData.append('files', file)
    })

    try {
      const response = await axios.post('/api/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      console.log('上传成功', response.data)
    } catch (error) {
      console.error('上传失败', error)
    }
  }
}

进度显示

添加上传进度显示功能,通过 axios 的 onUploadProgress 回调更新进度条。

<template>
  <div v-if="uploading">
    上传进度: {{ progress }}%
    <progress :value="progress" max="100"></progress>
  </div>
</template>

<script>
data() {
  return {
    uploading: false,
    progress: 0
  }
},
methods: {
  async uploadFiles() {
    this.uploading = true
    try {
      await axios.post('/api/upload', formData, {
        onUploadProgress: progressEvent => {
          this.progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
        }
      })
    } finally {
      this.uploading = false
    }
  }
}
</script>

文件限制

添加文件类型和大小限制,在上传前进行验证。

methods: {
  handleFileChange(event) {
    const files = Array.from(event.target.files)
    const validFiles = files.filter(file => {
      const isValidType = ['image/jpeg', 'image/png'].includes(file.type)
      const isValidSize = file.size < 2 * 1024 * 1024 // 2MB
      return isValidType && isValidSize
    })
    this.files = validFiles
  }
}

拖放上传

实现拖放文件上传功能,提升用户体验。

<template>
  <div 
    class="drop-zone"
    @dragover.prevent="dragover"
    @dragleave.prevent="dragleave"
    @drop.prevent="drop"
    :class="{ 'drag-active': isDragActive }"
  >
    拖放文件到这里
  </div>
</template>

<script>
data() {
  return {
    isDragActive: false
  }
},
methods: {
  dragover() {
    this.isDragActive = true
  },
  dragleave() {
    this.isDragActive = false
  },
  drop(event) {
    this.isDragActive = false
    this.handleFileChange(event)
  }
}
</script>

组件封装

将组件封装为可复用的形式,通过 props 接收配置参数,通过 emits 触发事件。

vue实现附件组件

<script>
export default {
  props: {
    maxSize: {
      type: Number,
      default: 2 * 1024 * 1024
    },
    allowedTypes: {
      type: Array,
      default: () => ['image/jpeg', 'image/png']
    }
  },
  emits: ['upload-success', 'upload-error'],
  methods: {
    async uploadFiles() {
      try {
        const response = await axios.post('/api/upload', formData)
        this.$emit('upload-success', response.data)
      } catch (error) {
        this.$emit('upload-error', error)
      }
    }
  }
}
</script>

标签: 组件附件
分享给朋友:

相关文章

Vue组件实现方法

Vue组件实现方法

Vue组件的基本实现方法 Vue组件是Vue.js的核心概念之一,用于构建可复用的UI模块。以下是Vue组件的几种常见实现方式: 单文件组件(SFC) 使用.vue文件格式,将模板、脚本和样式封装在…

uniapp组件

uniapp组件

uniapp组件基础概念 uniapp的组件系统基于Vue.js,支持跨平台开发(H5、小程序、App等)。组件分为内置基础组件(如<view>、<button>)和自定义组件…

vue抽屉组件实现

vue抽屉组件实现

Vue 抽屉组件实现 使用 Element UI 实现 Element UI 提供了现成的抽屉组件 el-drawer,可以快速实现抽屉效果。 安装 Element UI: npm install…

vue实现日历组件

vue实现日历组件

Vue 日历组件实现步骤 基础结构搭建 使用Vue 3的Composition API或Options API创建组件框架。核心结构包括年份/月份切换按钮、星期标题栏和日期网格。 <t…

vue 实现动态组件

vue 实现动态组件

Vue 动态组件的实现方法 在 Vue 中,可以通过 <component> 标签结合 is 属性实现动态组件切换。以下是具体实现方式: 使用 is 属性绑定组件名 <templ…

vue 滑杆组件实现

vue 滑杆组件实现

实现基础滑杆组件 使用Vue的v-model和原生<input type="range">实现基础功能: <template> <div> <i…