vue实现导入功能
文件上传组件实现
使用Vue的<input type="file">元素结合@change事件处理文件选择。创建基础文件上传组件:
<template>
<div>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">上传</button>
</div>
</template>
<script>
export default {
data() {
return {
selectedFile: null
}
},
methods: {
handleFileChange(event) {
this.selectedFile = event.target.files[0]
},
uploadFile() {
if (!this.selectedFile) return
const formData = new FormData()
formData.append('file', this.selectedFile)
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log('上传成功', response.data)
}).catch(error => {
console.error('上传失败', error)
})
}
}
}
</script>
Excel文件解析
对于Excel文件导入,可以使用xlsx库处理:
import XLSX from 'xlsx'
methods: {
parseExcel(file) {
const reader = new FileReader()
reader.onload = (e) => {
const data = new Uint8Array(e.target.result)
const workbook = XLSX.read(data, { type: 'array' })
const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
const jsonData = XLSX.utils.sheet_to_json(firstSheet)
this.$emit('parsed', jsonData)
}
reader.readAsArrayBuffer(file)
}
}
CSV文件处理
纯前端解析CSV文件:

methods: {
parseCSV(file) {
const reader = new FileReader()
reader.onload = (e) => {
const content = e.target.result
const lines = content.split('\n')
const headers = lines[0].split(',')
const result = []
for (let i = 1; i < lines.length; i++) {
const obj = {}
const currentLine = lines[i].split(',')
for (let j = 0; j < headers.length; j++) {
obj[headers[j]] = currentLine[j]
}
result.push(obj)
}
this.$emit('parsed', result)
}
reader.readAsText(file)
}
}
后端接口对接
创建与后端API对接的方法:
methods: {
async sendImportData(data) {
try {
const response = await axios.post('/api/import', {
importData: data
})
return response.data
} catch (error) {
throw new Error(`导入失败: ${error.message}`)
}
}
}
进度反馈实现
添加上传进度指示:

methods: {
uploadFile() {
const config = {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
this.uploadProgress = percentCompleted
}
}
axios.post('/api/upload', formData, config)
.then(/* ... */)
}
}
错误处理增强
完善错误处理机制:
methods: {
async uploadFile() {
try {
// ...上传逻辑
this.$notify({
title: '成功',
message: '文件导入成功',
type: 'success'
})
} catch (error) {
let message = '导入失败'
if (error.response) {
message = error.response.data.message || message
}
this.$notify.error({
title: '错误',
message
})
}
}
}
完整组件示例
组合各功能的完整组件:
<template>
<div class="importer">
<input
type="file"
accept=".csv,.xlsx,.xls"
@change="handleFileChange"
/>
<div v-if="isLoading">
导入中... {{ progress }}%
<progress :value="progress" max="100"></progress>
</div>
<button
:disabled="!selectedFile || isLoading"
@click="startImport"
>
开始导入
</button>
<div v-if="importResult" class="result">
成功导入 {{ importResult.imported }} 条记录
<span v-if="importResult.skipped > 0">
(跳过 {{ importResult.skipped }} 条)
</span>
</div>
</div>
</template>
<script>
import XLSX from 'xlsx'
export default {
data() {
return {
selectedFile: null,
isLoading: false,
progress: 0,
importResult: null
}
},
methods: {
// ...之前的方法组合
async startImport() {
this.isLoading = true
try {
let parsedData
if (this.selectedFile.name.endsWith('.xlsx') ||
this.selectedFile.name.endsWith('.xls')) {
parsedData = await this.parseExcel(this.selectedFile)
} else {
parsedData = await this.parseCSV(this.selectedFile)
}
this.importResult = await this.sendImportData(parsedData)
} finally {
this.isLoading = false
}
}
}
}
</script>






