Vue - read csv/tsv in browser

by Christopher O

HTML

<div id="app" v-cloak>
  <h2>Upload List of Names</h2>
  <input type="file" ref="myFile" @change="selectedFile"> 
  <input type="submit" value="Upload File" />
  <div v-if="allNames.length">
    <br><p>Your file contains {{allNames.length}} items. Here's the first ten:</p><br>
    <ul>
      <li v-for="name in names">{{name}}</li>
    </ul>
  </div>
</div>

CSS

body {
  padding: 15px;
}
[v-cloak] {display: none}

Vue

Vue.config.productionTip = false;
Vue.config.devtools = false;

const app = new Vue({
  el:'#app',
  data: {
    allNames:[]
  },
  computed:{
    names() {
      return this.allNames.slice(0,10);
    }
  },
  methods:{
    selectedFile() {
      console.log('selected a file');
      console.log(this.$refs.myFile.files[0]);
      
      let file = this.$refs.myFile.files[0];
      //if(!file || file.type !== 'text/plain') return;
      if(!file || !file.type.startsWith('text/')) return;
      
      // Credit: https://stackoverflow.com/a/754398/52160
      let reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      
      reader.onload = evt => {
        let text = evt.target.result;
        this.allNames = text.split(/\r?\n/);
        //empty string at end?
        if(this.allNames[this.allNames.length-1] === '') this.allNames.pop();
      }
      
      reader.onerror = evt => {
        console.error(evt);
      }
      
    }
  }
})