For example, you want to make a portfolio of your projects. It would be a cool feature on your website to have the picture of your project move on hover.
With this small tutorial, it will allow you to activate a .gif when hovered over a picture.
1. Set up vue project
Create your vue-project, follow the steps and cd
into it.
vue create vue-hover-picture
2. Clean up project
For this, we'll stick to the HelloWorld.vue
component. Get rid of all the code in both HelloWorld.vue
and the App.vue
component.
Load the image in the HelloWorld.vue
component, like below.
<template>
<div class="hello">
<img :src="pictureStatic">
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
pictureStatic: require("../assets/todo.png")
}
}
}
</script>
<style scoped>
img {
height: 500px;
}
</style>
We now have a picture loaded in our component. We want this picture to become a .gif
when we're hovering.
3. Hover function
In vue, we can use @mouseover
and @mouseleave
events. We can pass in the boolean hover
where it will be true
in the @mouseover
event and, surprise, false
with @mouseleave
.
As we're using this in our code and using it further on in a function, add it to our data and set it to false
. Let's also import our .gif
.
export default {
name: 'HelloWorld',
data () {
return {
pictureStatic: require("../assets/todo.png"),
pictureGif: require("../assets/todo.gif"),
hover: false
}
}
}
Next, we are going to use a function to determine the src
of our image, whether it's hovered or not.
Add the computed
part and write a new function, let's call it pictureHover
. So we can write out a simple function, using hover
as our conditional statement.
computed: {
pictureHover () {
if (this.hover == true) {
return this.pictureGif
} else {
return this.pictureStatic
}
}
}
Now we should change our html code of the image. We can pass in this function pictureHover()
to our src
attribute of our image:
<img :src="pictureHover" @mouseover="hover = true" @mouseleave="hover = false">
And that's it! You can now put in a small live preview of your project when people hover over the picture.
Top comments (2)
Hello
Have you solved the problem of constant request for resources?
dev-to-uploads.s3.amazonaws.com/up...
Keep static image files in
/static/images
folder.That way it never gets rebuilt.