It is how to use FileReader which is a web api of JavaScript on Vue.js.
I created it in the form of importing the image as a sample.
See below for more information on FileReaderWeb API–FileReader–MDN
Html part, file loading form explanation
It is implemented so that when you select an image, the selected image is displayed.
<template lang="html"> <div> <div v-if="selectedImageUrl"> <img :src="selectedImageUrl"> </div> <label> <span>Select File</span> <input type="file" @change="changeImg" > <input type="text" id="imageLoader" disabled="" :placeholder="loadedImage ? loadedImage.name : 'Please choose the file'" > </label> </div> </template>
Input type="file"
file read input installed
selectedImageUrl
Displays image when there is an imported image file
@change
changeImage
call onchange
It is roughly such a condition.
JavaScript part — FileReader used part
This time I'm implementing it in data URI Scheme
.
<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>
Create an instance with new FileReader()
.
Because the FileReader API is asynchronous, there are events that you can use to retrieve the state.
An onload
event is required to access data when the file is read.
reader.readAsDataURL()
is loading the file with data URI Scheme
.
It's easy, but I wrote about how to implement FileReader in Vue.js.
VUE.JS Recommended Books
I think that you are a reader of books, but I realize that you can learn more deeply by implementing them in the field.
On the other hand, if you focus on implementation, you will not be able to think of better coding, so it is recommended that you read the book again.
Vue.js 3 Cookbook: Discover actionable solutions for building modern web apps with the latest Vue features and TypeScript