Vue.js with its super fast reactivity makes reactive development a breeze. Here in this example, you’ll learn how you can enlarge or zoom in an image on hover in Vue.js. Here’s the code I’ve written, I’ll explain the functionality in a bit:
<template>
<div id="app">
<div class="np-credits">wwww.nightprogrammer.com</div>
<div>
<img
:src="$options.imageSource"
:class="{
'img-default-size': true,
'img-enlarged-size': imageEnlarged,
}"
@mouseover="enlargeImage"
@mouseout="shrinkImage"
/>
</div>
</div>
</template>
<script>
export default {
name: "App",
created() {
this.$options.imageSource =
"https://images.unsplash.com/photo-1564507592333-c60657eea523";
},
data() {
return {
imageEnlarged: false,
};
},
methods: {
enlargeImage() {
console.log("enlarged");
this.imageEnlarged = true;
},
shrinkImage() {
this.imageEnlarged = false;
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
padding: 24px;
}
.img-default-size {
height: 200px;
transition: all 0.2s;
}
.img-enlarged-size {
height: 400px;
transition: all 0.2s;
}
.np-credits {
font-size: 12px;
margin-bottom: 12px;
color: #4b4b4b;
}
</style>
Code language: HTML, XML (xml)
In the above file, I’ve place an image source in the imageSource variable. I’ve then bind the source to the src attribute of img tag on line 6. Upon mouseover, I’ve set the value of imageEnlarged state to true. And upon mouseout, I’ve set it’s value to false. Whenever the value of imageEnlarged is set to true, img-enlarged-size class will be auto-bind to the img tag. This will result in an enlarged view of the image.
You can find a working copy of the above code below: