[Vuejs]-How can I handle click on file input with Vue?

1👍

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>

Leave a comment