How to check an image is loaded or not in VueJS ?
Last Updated :
25 Jul, 2021
While inserting an Image in a VueJS project, it may fail to load due to the following reasons:
- Writing wrong image URL.
- Due to poor connection
Approach: We are going to use an event in <img> to check whether an image is loaded or not in VueJS, the event we are going to use is:
- @load: The @load event gets triggered when the image is loaded and it gets executed.
Project Setup:
Step 1: Create a Vue Project using the following command in the command line:
vue create image-load
Note: We have taken ‘image-load‘ as the name of the Project, you can choose any name according to your choice.
- The ‘image-load’ Folder will be created.
- Open the folder in your Code Editor.
The project structure will look like this:
Step 2: After creating the project, add an image in the ‘assets folder’. We have added an image with the name – ‘gfg.png‘
Example: In this example, we are going to follow the following steps:
- In this example, we’re going to Insert an Image on the index page of our application.
- In the project “image-load“, we create a data variable ‘isLoaded‘ which has the default value “False“.
- A ‘description‘ data variable is also created which holds the Heading of the Page i.e “How to check if an image is loaded in VueJs?”.
- Assign a ‘@load‘ event to the Image.
- The name of the event will be ‘loadImage‘, and its function will be to change the value of ‘isLoaded‘ to “True” if the image gets loaded.
- And at last, we will print the value of ‘isLoaded‘ on our homePage, with the Image.
Now let’s see each step one by one with the implementation.
App.vue
< template >
< div >
< h1 >{{description}}</ h1 >
< br >
< img src = "./assets/gfg.png" alt = "" @ load = "loadImage" >
< h2 >Image Loaded : {{isLoaded}} </ h2 >
</ div >
</ template >
< script >
export default {
name: 'App',
data() {
return {
description: "How to check if Image "
+ "is Loaded in Vue.js or not?",
isLoaded: false,
};
},
methods: {
loadImage() {
this.isLoaded = true;
}
}
}
</ script >
< style >
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</ style >
|
Run the application: In the command line, enter the following command:
npm run serve
Output: Open the browser and go to http://localhost:8080/ and you will see the following output:
Explanation: As we can see, we had Initialised “isLoaded” to False initially. The image gets loaded and ‘isLoaded‘ is assigned a True value and ‘isImageLoaded’ value is then fetched and displayed with the Image during Output.
Share your thoughts in the comments
Please Login to comment...