首页 > 解决方案 > 如何在不使用 vue/javascript 中的 event.target 的情况下显示上传的 zip 文件的名称?

问题描述

我有一个输入,它接受文件类型并接受特定的 zip 文件。一旦动态上传到相关的输入标签中,我想显示 zip 文件的名称。现在我可以使用一种方法检索文件的名称,但它需要event从输入中获取。当我收到此错误时,尝试动态呈现文件名时失败:

app.js:164890 [Vue warn]: Error in render: "TypeError: Cannot read property 'target' of undefined"

如果我e在调用时通过了,{{fileName(e)}}那么我会收到此错误

[Vue warn]: Property or method "e" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property

这是我的 HTML 标签:

<input
   id="zip"
   name="zip"
   type="file"
   accept="application/zip"
   required>
          
   <label for="zip">{{fileName()}}</label>

Vue方法

fileName(e) {
      return e.target.files[0].name ? return e.target.files[0].name : 'Choose File';
    }

标签: javascriptvue.js

解决方案


change您可以通过事件处理程序监听输入事件,并在用户每次选择文件时检索文件名。

new Vue({
  el: "#app",
  data: {
      fileName: "Choose File",
  },
  methods: {
      fileSelected: function(e){
          this.fileName = e.target.files[0].name;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<input
   id="zip"
   name="zip"
   type="file"
   accept="application/zip"
   required
   v-on:change="fileSelected">
          
   <label for="zip">{{fileName}}</label>
</div>


推荐阅读