简体   繁体   中英

How can I handle click on file input with Vue?

I want to handle the cancel press when uploading a file

在此处输入图像描述

I looked at some examples that were implemented using pure JavaScript here is an example

All these examples work fine, I tried to implement this example using Vue JS, but it does not work correctly for me

<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>

You can see an example of my code in codesandbox

As stated in the comments, there isn't an event to capture canceling and you would be better off just adding a submit button.

Having said that, this will tell you if files were uploaded when the next 'mouseenter' event is fired on the body. It won't tell you if the cancel button was clicked.

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM