Vue scope: how to delay handling of @mouseover

Viewed 6745

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?

5 Answers
<div @mouseover="activarOver" @mouseleave="resetOver "> eventos </div>



data: () => {
    return {
      countMouseOver: 0
    }
  },
methods: {
    activarOver () {
      this.countMouseOver++
      if (this.countMouseOver < 2) {
        this.setMostrarPopup()
      }
      console.log(this.countMouseOver)
    },
    resetOver () {
      this.countMouseOver = 0
      console.log('reset')
    },
}

Implementation to show when hovered over for 1 second, then disappear when no longer hovered.

<span @mouseover="hover" @mouseleave="unhover">Hover over me!</span>
<div v-if="show">...</div>

data() {
   return {
      show: false;
      hovering: false,
   };
},
methods: {
    hover() {
       this.hovering = true;
       setTimeout(() => this.show = this.hovering, 1000);
    },
    unhover() {
       this.hovering = false;
       this.show = false;
    },
}

I have been solving this problem for selecting items in a list only if the user hovers for some time (to prevent menu flickering)

Template (pug):

.div(
    @mouseover="select(identifier)"
    @mouseout="clear()"
) {{content}}

Data:

hovered: false
selectedId: ""

and the methods

select(identifier) {
    this.selectedId = identifier
    setTimeout(() => {
        if(this.selectedId === identifier )
            this.hovered = true
        },
        1000
    )
},
clear() {
    this.selectedId = ''
}

the approach is to check if whatever user is hovering on is the same as they were hovering on a second ago.

If you want to use old syntax, bind 'this' to the setTimeout function

data() {
    return {
        hovered: false
    }
}

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