Categories
Vue Answers

How to Watch for File Input File Selection Change Events in Vue.js?

Spread the love

Sometimes, we want to watch a file input for file selection change events in Vue.js.

In this article, we’ll look at how to watch a file input for file selection change events in Vue.js.

Watch for File Input File Selection Change Events in Vue.js

We can watch a file input for file selection change events in Vue.js by listening to the change event.

To do that, we use the @change directive by writing:

<template>
  <div id="app">
    <input type="file" @change="previewFiles" multiple />
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    previewFiles(event) {
      console.log(event.target.files);
    },
  },
};
</script>

Also, we set the value of @change to the previewFiles method.

And then when we select files with the file input, we can get the file list with the selected files with the event.target.files property.

We can also assign a ref to the file input and use that to reference the file input in the method.

To do this, we write:

<template>
  <div id="app">
    <input type="file" ref="myFiles" @change="previewFiles" multiple />
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    previewFiles() {
      console.log(this.$refs.myFiles.files);
    },
  },
};
</script>

We set the ref prop to myFiles and then get the selected files with this.$refs.myFiles.files .

Conclusion

We can watch a file input for file selection change events in Vue.js by listening to the change event.

Also, we set the value of @change to the previewFiles method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *