【问题标题】:Getting error specifically when using <v-file-unput>使用 <v-file-input> 时特别出错
【发布时间】:2022-01-16 07:28:33
【问题描述】:

我正在使用 VueJSvuetify。我有一个触发函数@click 的输入标签和按钮,一旦我更改为v-file-input 组件,就会出现错误。

这里是代码 - 脚本和模板:

<script>
import papa from "papaparse";
export default {
  name: "CompareInput",
  data() {
    return {
      csvData: [],
    };
  },
  methods: {
    csvToJson() {
      let csvFile = this.$refs.file.files[0];
      if (csvFile == undefined) {
        alert("Please select a file to convert");
        this.csvData = [];
        return;
      }
      papa.parse(csvFile, {
        header: true,
        dynamicTyping: true,
        skipEmptyLines: true,
        preview: 100,
        complete(result) {
          this.csvData = result.data;
          for (let item of this.csvData) {
            console.log(item.input_fullName);
          }
          console.log(this.csvData);
        },
      });
    },
  },
};
</script>
<template>
  <div class="app">
    <h3>CSV Parser</h3>

    <v-file-input multiple ref="file" type="file"> </v-file-input>
    <v-btn @click="csvToJson" class="primary">Submit</v-btn>
  </div>
</template>
错误 - 无法读取未定义的属性(读取“0”)

同样,使用常规输入标记一切正常。

【问题讨论】:

    标签: javascript html vue.js vuetify.js


    【解决方案1】:

    我猜你误会了@JenifferJin answer

    你的错误在这一行:

    let csvFile = this.$refs.file.files[0];
    

    您正在引用 v-file-input 组件,但尝试像使用原生 HTML input 标记一样使用它。不应该这样做。

    v-file-input 不直接包含 files 字段。如果您编写这样的内容并查看浏览器控制台,您可以自己看到这一点:

    ...
    csvToJson() {
      console.log(this.$refs.file)
      ...
    }
    ...
    

    当您使用v-file-input 时,您应该使用v-model 来存储您的文件(或多个文件)。

    所以答案是:

    <v-file-input
      v-model="filesModel"
      multiple
      type="file">
    </v-file-input>
    ...
    data() {
      return {
        filesModel: [],
      };
    },
    ...
    methods: {
      csvToJson() {
        if (this.filesModel === null 
            || this.filesModel === undefined 
            || this.filesModel.length === 0) {
            alert("Please select a file to convert");
            return;
        }
        let csvFile = this.filesModel[0];
        ...the rest of your code
      },
    },
    

    There's a CodePen 可以帮助您了解v-file-inputinput 之间的区别。

    【讨论】:

    • 感谢详细的解释,我现在遇到了问题,并使其适用于多个文件和我的项目的其余部分。
    【解决方案2】:

    这是我的经验:

    <v-file-input
        show-size counter
        accept="video/*"
        v-model="video"
        @change="onVideo"
    >
    </v-file-input>
    

    在 Vue.js 的方法中:

    onVideo: function () {
        console.log(this.video)
    }
    

    【讨论】:

    • 还是有同样的问题...
    • 你使用的是什么版本的 Vue.js?
    • 当前版本的 Vuetify 不支持 Vue 3
    • Vuetify- 2.6.1 Vue- 2.6.14
    • 你应该删除 ​​ 按钮。
    猜你喜欢
    • 1970-01-01
    • 2022-08-22
    • 2020-11-11
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2021-04-29
    • 2020-04-14
    • 2021-09-05
    相关资源
    最近更新 更多