vue 实现文件列表
实现文件列表的基本结构
使用 Vue 实现文件列表需要结合组件化开发思想,通常通过 v-for 指令动态渲染文件数据。以下是一个基础的文件列表组件示例:
<template>
<div class="file-list">
<div v-for="file in files" :key="file.id" class="file-item">
<span>{{ file.name }}</span>
<span>{{ file.size }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
files: [
{ id: 1, name: 'document.pdf', size: '2.4 MB' },
{ id: 2, name: 'image.jpg', size: '1.8 MB' }
]
}
}
}
</script>
<style scoped>
.file-item {
display: flex;
justify-content: space-between;
padding: 8px;
border-bottom: 1px solid #eee;
}
</style>
动态加载文件数据
实际项目中,文件数据通常通过 API 异步获取。可以使用 axios 或 fetch 实现:

<script>
import axios from 'axios';
export default {
data() {
return {
files: [],
isLoading: false
}
},
async created() {
this.isLoading = true;
try {
const response = await axios.get('/api/files');
this.files = response.data;
} catch (error) {
console.error('Failed to load files:', error);
} finally {
this.isLoading = false;
}
}
}
</script>
添加文件操作功能
为文件列表增加下载、删除等交互功能:
<template>
<div class="file-actions">
<button @click="downloadFile(file.id)">Download</button>
<button @click="deleteFile(file.id)">Delete</button>
</div>
</template>
<script>
methods: {
async downloadFile(id) {
const file = this.files.find(f => f.id === id);
window.open(`/api/files/download/${id}`, '_blank');
},
async deleteFile(id) {
try {
await axios.delete(`/api/files/${id}`);
this.files = this.files.filter(file => file.id !== id);
} catch (error) {
console.error('Delete failed:', error);
}
}
}
</script>
实现文件上传功能
扩展组件以支持文件上传:

<template>
<div>
<input type="file" @change="handleFileUpload" multiple>
<button @click="uploadFiles">Upload</button>
</div>
</template>
<script>
methods: {
handleFileUpload(event) {
this.selectedFiles = Array.from(event.target.files);
},
async uploadFiles() {
const formData = new FormData();
this.selectedFiles.forEach(file => {
formData.append('files', file);
});
try {
await axios.post('/api/files', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
});
this.refreshFileList();
} catch (error) {
console.error('Upload failed:', error);
}
}
}
</script>
使用第三方组件库
对于更复杂的文件管理需求,可以考虑使用现成的 UI 组件库:
<template>
<el-upload
action="/api/files"
:on-success="handleSuccess"
:file-list="files">
<el-button type="primary">Click to upload</el-button>
</el-upload>
</template>
<script>
import { ElUpload, ElButton } from 'element-ui';
export default {
components: { ElUpload, ElButton },
methods: {
handleSuccess(response) {
this.files.push(response.file);
}
}
}
</script>
性能优化建议
对于大型文件列表,建议实现虚拟滚动或分页加载:
data() {
return {
currentPage: 1,
pageSize: 20,
totalFiles: 0
}
},
methods: {
async loadMoreFiles() {
const response = await axios.get('/api/files', {
params: { page: this.currentPage, size: this.pageSize }
});
this.files = [...this.files, ...response.data.items];
this.totalFiles = response.data.total;
}
}
以上实现方式可以根据具体项目需求进行调整和扩展。






