This article explains how to use FileReader, a JavaScript web API, within a Vue.js application.
HTML SECTION: FILE UPLOAD FORM EXPLANATION
It is implemented such that when an image is selected, the chosen image is displayed.
<template lang="html">
<div>
<div v-if="selectedImageUrl">
<img :src="selectedImageUrl">
</div>
<label>
<span>ファイル選択</span>
<input
type="file"
@change="changeImg"
>
<input type="text" id="imageLoader" disabled=""
:placeholder="loadedImage ? loadedImage.name : 'ファイルを選択してください'"
>
</label>
</div>
</template>An `input type="file"` element is placed for file selection.
`selectedImageUrl`: Displays the image when a file has been loaded.
`loadedImage`: Displays the name of the loaded image. If no image is selected, it displays 'Please select a file'.
JAVASCRIPT SECTION: FILEREADER USAGE
<script>
export default {
data: function() {
return {
selectedImageUrl: null,
loadedImage: null,
}
},
methods: {
changeImage(e) {
let that = this
that.loadedImage = e.target.files[0]
let reader = new FileReader()
reader.onload = function (e) {
that.selectedImageUrl = e.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
}
}
</script>An instance is created using `new FileReader()`.
The FileReader API is asynchronous, so there are events you can use to track its status.
The `onload` event is required to access the data once the file has been read.
The file is read using the Data URI Scheme with `reader.readAsDataURL()`.
Although simple, I've outlined how to implement FileReader in Vue.js.
RECOMMENDED VUE.JS BOOKS
While reading books is important, I truly feel that implementing things in a real-world setting leads to deeper learning.
Conversely, if you only focus on implementation, you might miss out on opportunities to think about better coding practices, so I recommend revisiting books as well.
For those who have some knowledge of JavaScript and Vue.js.
📦