vue实现附件组件
vue实现附件组件
基本组件结构
使用Vue的<input type="file">元素作为基础,结合自定义样式和功能扩展。通过v-model或事件绑定实现文件选择逻辑。
<template>
<div class="attachment-upload">
<input
type="file"
ref="fileInput"
@change="handleFileChange"
multiple
style="display: none"
>
<button @click="triggerFileInput">选择文件</button>
<ul v-if="files.length > 0">
<li v-for="(file, index) in files" :key="index">
{{ file.name }}
<button @click="removeFile(index)">删除</button>
</li>
</ul>
</div>
</template>
数据与事件处理
通过data或ref维护文件列表,实现文件选择、删除和预览功能。

<script>
export default {
data() {
return {
files: []
}
},
methods: {
triggerFileInput() {
this.$refs.fileInput.click()
},
handleFileChange(e) {
const selectedFiles = Array.from(e.target.files)
this.files = [...this.files, ...selectedFiles]
this.$emit('files-selected', this.files)
},
removeFile(index) {
this.files.splice(index, 1)
this.$emit('files-updated', this.files)
}
}
}
</script>
样式优化
添加CSS美化组件外观,例如使用图标库或自定义样式增强用户体验。
.attachment-upload {
border: 2px dashed #ccc;
padding: 20px;
text-align: center;
}
.attachment-upload button {
background: #42b983;
color: white;
padding: 8px 16px;
border: none;
cursor: pointer;
}
ul {
list-style: none;
padding: 0;
}
li {
display: flex;
justify-content: space-between;
margin-top: 8px;
}
高级功能扩展
支持文件类型限制、大小校验和上传进度显示。

<script>
export default {
props: {
maxSize: {
type: Number,
default: 10 * 1024 * 1024 // 默认10MB
},
allowedTypes: {
type: Array,
default: () => ['image/jpeg', 'application/pdf']
}
},
methods: {
handleFileChange(e) {
const invalidFiles = Array.from(e.target.files).filter(file =>
!this.allowedTypes.includes(file.type) || file.size > this.maxSize
)
if (invalidFiles.length > 0) {
alert('包含不支持的文件类型或大小超限')
return
}
this.files = [...this.files, ...Array.from(e.target.files)]
}
}
}
</script>
服务端上传集成
通过axios或其他HTTP库实现文件上传,添加进度条功能。
<script>
import axios from 'axios'
export default {
methods: {
async uploadFiles() {
const formData = new FormData()
this.files.forEach(file => {
formData.append('attachments[]', file)
})
try {
const response = await axios.post('/api/upload', formData, {
onUploadProgress: progressEvent => {
const percent = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
this.$emit('upload-progress', percent)
}
})
this.$emit('upload-complete', response.data)
} catch (error) {
this.$emit('upload-error', error)
}
}
}
}
</script>
组件使用示例
在父组件中引入并使用附件组件,处理相关事件。
<template>
<div>
<AttachmentUpload
@files-selected="handleFiles"
@upload-progress="updateProgress"
/>
<div v-if="progress > 0">上传进度: {{ progress }}%</div>
</div>
</template>
<script>
export default {
data() {
return {
progress: 0
}
},
methods: {
handleFiles(files) {
console.log('Selected files:', files)
},
updateProgress(percent) {
this.progress = percent
}
}
}
</script>






