Search code examples
javascriptscopevue.jsdelaymouseover

Vue scope: how to delay handling of @mouseover


So I want to have an action only if the user has the mouse on the div for at least 1 second. Inside template:

<div @mouseover="trigger"></div>

Inside script:

data() {
    return {
        hovered: false
    }
}

methods: {
    trigger() {
        setTimeout(function(){ this.hovered = true }, 1000)
    }
}

My problem is that I don't understand the scope of Vue. Because this.hovered is inside another function, it does not find the actual hovered data variable. What's the solution to this?


Solution

  • Have you tried using an arrow function in your setTimeout? It will maintain this.

    data() {
        return {
            hovered: false
        }
    }
    
    methods: {
        trigger() {
            setTimeout(() => { this.hovered = true }, 1000)
        }
    }