I have a vue project, where I want to select a local .csv and import the contents to a variable. I'm trying to do so via vue-papa-parse, which I've installed via npm. The following code (main.js, then a vue component) selects a file in browser but does nothing after that. The only hint in the console is an 'underfined' at ma-map.vue:33 (the console.log line).
The papa parse documentation mentions the config object should include a callback, which I haven't (and don't know how).
I'm not welded to the idea of papa parse but it seemed to have good reviews. Feedback appreciated.
The 'main.js' file:
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>
I had the same problem, I used the above code but I can't dynamically update my vue data
for example this.availability
is undefined
inside the complete
config
.
I solved it by creating another method
and placed it to complete
as a callback. Now, I am able to pass data to this.availability
and update some UI
.
<script>
export default {
data: function () {
return {
availability: {}
}
},
methods: {
onComplete(results, file){
// Your logic here! functions or axios calls
this.availability = results;
console.log(this.availability);
},
readFile() {
/* return first object in FileList */
var file = event.target.files[0];
this.$papa.parse(file, {
header: true,
complete: this.onComplete // your vue methods
});
}
}
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With