gsundberg
gsundberg

Reputation: 547

Importing Files with nuxt.js (Vue equivalent of getElementById())

I'm having trouble loading a file in one of my components. It worked before I moved to Vue using getElementById(). Here is what I have tried: In template:

<input type="file" accept=".obj" id="file" ref="OBJImport" name="objFile" @change="loadFileAsText()" single />

In data:

data(){
    return {
         files: []
    }
}

In methods:

methods: {  
    loadFileAsText: function() {
        if(process.client) {
            this.files = this.$refs.OBJImport.files[0];
            console.log(files);
         }
    }

But when I try to upload the file, I get:

ReferenceError: files is not defined

I have also tried without the [0]. Changing .files[0] to .file still yields the same error for files. What should I do to get my file from the template to my methods? Thanks!

Upvotes: 0

Views: 470

Answers (1)

sugars
sugars

Reputation: 1493

Remove () from the change event:

<input type="file" accept=".obj" id="file" ref="OBJImport" name="objFile" @change="loadFileAsText" single />

Use the default event parameter

methods: {  
  loadFileAsText: function(e) {
    if(process.client) {
      //this.files = this.$refs.OBJImport.files[0];
      //console.log(files); // Here is this.files, not files, this is your initial error.
      this.files = e.target.files[0];
      console.log(this.files);
  }
}

The files you log does not exist, this is your only error. In addition, I have provided another way to get files.

Upvotes: 1

Related Questions