'i is not defined' FileReader.reader.onload VueJs

'i is not defined' at FileReader.reader.onload VueJs

我无法在数组中执行 for 循环或 forEach,因为它说我没有定义

我已经试过用while, a for, a for each。使用 i 就像一个 Vue 数据变量。 我设置 let self = this,因为范围在 reader.onload 内发生变化。而且我知道问题必须出在类似的东西上。

<template>
  <div>
    <p>My File Selector: <file-select v-model="file"></file-select></p>
    <p v-if="file">{{file.name}}</p>
    <v-btn v-if="file" @click="importFile">Import</v-btn>
    <div id="fileContents">

    </div>
  </div>
</template>

<script>
  import icsToJson from 'ics-to-json'
  import FileSelect from './FileSelect.vue'

    export default {
        name: "ViewImport",
        components: {
          FileSelect
        },
        data(){
          return {
            file: null,
            fileInJson: null,
            categories: [],
            importExists: false,
            i
          }
        },
        created(){
            this.getCategories();
        },
        methods:{
            getCategories(){
              //this works 
           },
            importCreatingCategoryImport(){
              //code, this works 
            },
            doesImportExists(){
              for (var i = 0; i < this.categories.length; i++){
                if (this.categories[i].category.name === 'Import'){
                  this.importExists = true;
                  // break;
                }
              }
            },
            importFile(){
              if (this.file) {
                let reader = new FileReader();
                reader.readAsText(this.file, "UTF-8");
                let self = this;
                reader.onload = function (evt) { //If everything works 
                  //Changes the file to format JSON 
                  self.fileInJson = icsToJson(evt.target.result);

                  self.doesImportExists();//the loop

                  if (self.importExists){
                      console.log('Category exists');
                      //other method
                  }else{
                      console.log('not working'); //Because its in my BD
                    // self.importCreatingCategoryImport();
                  }

                };
                reader.onerror = function (evt) { //if it doesn't
                  document.getElementById("fileContents").innerHTML = "error reading file";
                }
              }
            },

        }
    }
</script>
//style commented

那是因为在您的 data 部分中您没有为键 i 赋值。您应该在数据中执行 i : 0,并在 for 循环中执行 let j = this.i; j < this.categories.length; j++)

最后,我更改了 reader.onload 中函数中的所有内容,但使用 self 而不是 this。可读性较差,但有效。