Reputation:
asked a similar question earlier but i've been stuck at this for a while.
i have a div that v-shows on certain events, for example when hovering over div1
and clicking on div2
. i want to make so this div disappears when the mouse hasn't touched it for a certain amount of time, let's say three seconds.
my problems are that i cant use v-on:mouseleave (because the div appears without the mouse being on it) so i'd need something that after a certain delay toggles v-show on the div. is there something i'm missing? what should i be using?
thanks!
Upvotes: 1
Views: 1561
Reputation: 32724
The simplest way is to use a component and add an event listener in the mounted hook that uses a timeout to set a flag attached to v-show
, so:
Vue.component('my-deiv', {
template: `<template id="block"><div v-show="show">A div</div></template>`,
mounted(){
this.$el.addEventListener('mousemove', () => {
setTimeout( () => {
this.show = false;
}, 3000)
})
},
data(){
return{
show: true
}
}
});
Now whenever the mouse moves over the div it fires the timeout, here's the JSFiddle: https://jsfiddle.net/nb80sn52/
EDIT
If you want to hide the div
when the mouse has not moved on it for a certain amount of time - but not when the mouse exits, then you can restart the timeout each time the mouse moves and then cancel it altogether when the mouse leaves, here's the updated version:
Vue.component('block', {
template: "#block",
mounted() {
this.timer = null;
this.$el.addEventListener('mousemove', () => {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.show = false;
}, 3000)
})
this.$el.addEventListener('mouseleave', () => {
clearTimeout(this.timer);
})
},
data() {
return {
show: true
}
}
})
And the JSFiddle for that: https://jsfiddle.net/utaaatjj/
Upvotes: 1
Reputation: 6507
You could setTimeout
in your component render function (or any other function) which would change this.visible = true
to this.visible = false
after a predefined period of time.
Upvotes: 0