csv - 如何使用 vue-papa-parse 将本地 csv 文件导入 vue?
问题描述
我有一个 vue 项目,我想在其中选择一个本地 .csv 并将内容导入一个变量。我正在尝试通过我通过 npm 安装的 vue-papa-parse 来做到这一点。以下代码(main.js,然后是 vue 组件)在浏览器中选择一个文件,但之后什么也不做。控制台中的唯一提示是 ma-map.vue:33(console.log 行)的“欠精细”。
papa parse 文档提到配置对象应该包含一个回调,我没有(也不知道如何)。
我不接受 papa parse 的想法,但它似乎有很好的评论。反馈表示赞赏。
“main.js”文件:
import Vue from 'vue'
import VuePapaParse from 'vue-papa-parse'
import vSelect from 'vue-select'
import 'vue-select/dist/vue-select.css'
import VueRouter from 'vue-router'
import PouchDB from 'pouchdb-browser'
import App from './App.vue'
import {
routes
} from './routes'
Vue.config.productionTip = false
Vue.component('v-select', vSelect)
Vue.use(VuePapaParse)
Vue.use(VueRouter)
...
<!-- Vue Component file -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js">
< template >
<
div >
<
h3 > Import csv < /h3> <
br / >
<
br / >
<
input type = "file"
@change = "readFile" / > <!-- implicit event should return FileList -->
<
/div> < /
template >
<
script >
export default {
data: function() {
return {
config: /* Papa Parse config object */ {
delimiter: "", // auto-detect
newline: "", // auto-detect
quoteChar: '"',
escapeChar: '"',
header: true,
dynamicTyping: true,
preview: 0,
encoding: "",
delimitersToGuess: [',', '\t', '|', ';']
// ?? callback function ??
}
}
},
methods: {
readFile() {
var fileToParse = event.target.files[0] /* returns first object in FileList */
this.parsedFile = this.$papa.parse(fileToParse, this.config); /* from similar syntax in https://www.npmjs.com/package/vue-papa-parse#parse-local-files */
console.log(this.parsedFile);
}
}
};
</script>
解决方案
我找到了我的答案,确实是在回调函数中,它需要作为papa.parse 函数中的配置选项传递。
以下适用于 Vue.js 环境并正确输出 csv 文件的内容。papa.parse 行使用 vue-papa-parse 包装语法,选项 'header: true' 和 'complete: function...' 根据 papa.parse 文档。
<script>
export default {
data: function () {
return {
availability: {}
}
},
methods: {
readFile() {
/* return first object in FileList */
var file = event.target.files[0];
this.$papa.parse(file, {
header: true,
complete: function (results) {
this.availability = results.data;
console.log(this.availability);
}
});
}
}
}
推荐阅读
- java - 使用 JDBI 3 执行任意 SQL(文件)
- r - 插入符号包中多个列的 createDataPartition
- python - 将字典值映射到另一个字典的最佳方法是什么
- sql-server - SQL 查询 - 按几列过滤有效和无效数据
- substring - 如何用可变数量的前导零填充字符串?
- autodesk-forge - 是否可以更改上传的文件?
- reactjs - 在 TS 中,如何定义子属性?
- javascript - 如果使用谷歌应用脚本达到条件,如何更新每行的现有谷歌工作表
- python - 在嵌套列表中查找唯一元素
- dialogflow-es - Google 对话流服务名称中的嵌入空格