【问题标题】:How can I handle click on file input with Vue?如何使用 Vue 处理单击文件输入?
【发布时间】:2022-02-04 00:32:03
【问题描述】:

我想在上传文件时处理取消按下

我查看了一些使用纯 JavaScript 实现的示例,这里是 example

所有这些示例都可以正常工作,我尝试使用 Vue JS 来实现这个示例,但它对我来说无法正常工作

<div>
   <label for="upload" @click="initialize">Upload File</label>
   <input type="file" id="upload" ref="theFile" hidden />
</div>

<script>
export default {
  methods: {
    initialize() {
      document.body.onfocus = this.checkIt;
      alert("initializing");
    },

    checkIt() {
      if (this.$refs.theFile.value.length) alert("Files Loaded");
      else alert("Cancel clicked");
      document.body.onfocus = null;
      alert("checked");
    },
  },
};
</script>

可以看my code in codesandbox的例子

【问题讨论】:

标签: javascript vue.js file input vuejs2


【解决方案1】:

如 cmets 中所述,没有捕获取消的事件,您最好添加一个提交按钮。

话虽如此,this 会在 body 上触发下一个 'mouseenter' 事件时告诉您文件是否已上传。它不会告诉你是否点击了取消按钮。

<template>
  <form>
    <label for="upload">Upload File</label>
    <input
      @click="onShowFileUpload"
      @change="onFileUpload"
      type="file"
      id="upload"
      ref="theFile"
      hidden
    />
  </form>
</template>

<script>
export default {
  methods: {
    onShowFileUpload() {
      this.$refs.theFile.value = "";
      const onHandleMouseEnter = () => {
        if (this.$refs.theFile.value.length === 0) {
          console.log("No files loaded");
        }
        document.body.removeEventListener("mouseenter", onHandleMouseEnter);
      };
      document.body.addEventListener("mouseenter", onHandleMouseEnter);
    },
    onFileUpload(event) {
      console.log("Files Uploaded");
    },
  },
};
</script>
<style>
html,
body {
  height: 100%;
  height: 100%;
}

label {
  font-family: sans-serif;
  font-size: 20px;
  border: 1px solid tomato;
  padding: 7px 15px;
  cursor: pointer;
}
</style>

【讨论】:

  • 这在某些使用键盘导航的情况下可能不起作用。关键是,如果您有重要的事情要做,不要依赖这样的技巧,否则您可能会以错误的方式解决问题。如果没有,那你很好。
  • 你说得对,我今天才发现你强调的这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
相关资源
最近更新 更多