我正在尝试编写我的第一个Vue应用,该应用将允许CSV上传并在表格中显示数据。我可以上传文件并将内容呈现到控制台,然后使用Papa解析CSV。不过,我似乎无法将文件中的数据绑定到表。我开始here,并添加了用于CSV处理的Papa解析。
以下是相关代码:
Main.js
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>'
})
Upload.vue组件
<template>
<h1>Upload CSV</h1>
<input type='file' @change='loadTextFromFile'>
</template>
<script>
// csv parsing
import Papa from 'papaparse'
export default {
methods: {
loadTextFromFile (event) {
if (!event.target.files[0]) {
alert('Upload a file.')
} else {
let file = event.target.files[0]
if (file) {
let reader = new FileReader()
let config = {
delimiter: ',',
newline: '',
quoteChar: '"',
escapeChar: '"',
header: false,
trimHeaders: false
}
// reader.onload = e => this.$emit('load', e.target.result)
reader.onload = e => this.$emit('load', Papa.parse(event.target.result, config))
// trace what was emitted
reader.onload = function (event) {
let results = Papa.parse(event.target.result, config)
console.log('PAPA RESULT: ', results.data)
console.log('ROWS:', event.target.result)
}
reader.readAsText(file)
} else {
alert('Please select a file to upload.')
}
}
}
}
}
</script>
<style>
</style>
App.vue
<template>
<div id="app">
<h1>My CSV Handler</h1>
<br>
<upload @load="items = $event"></upload>
<br>
<table>
<thead>
</thead>
<tbody>
<!-- eslint-disable-next-line -->
<tr v-for="row in items">
<td>{{ row }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import Upload from './components/Upload'
export default {
name: 'app',
data: () => ({ items: [] }),
components: {
Upload
}
}
</script>
<style>
</style>
如果我发出原始e.target.result
并将App.vue中的所有地方的“ items”更改为“ text”,则可以像本教程一样成功地将文本数据呈现到文本区域。
谢谢!