Vue 范围:如何延迟处理@mouseover

Vue scope: how to delay handling of @mouseover

所以我只想在用户将鼠标放在 div 上至少 1 秒时执行操作。内部模板:

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

内部脚本:

data() {
    return {
        hovered: false
    }
}

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

我的问题是我不了解 Vue.js 的范围。因为 this.hovered 在另一个函数中,所以它找不到实际悬停的数据变量。有什么解决办法?

您是否尝试过在 setTimeout 中使用箭头函数?它将保持 this.

data() {
    return {
        hovered: false
    }
}

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

我一直在解决这个问题,仅当用户悬停一段时间(以防止菜单闪烁)时才选择列表中的项目

模板(哈巴狗):

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

数据:

hovered: false
selectedId: ""

和方法

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

该方法是检查用户悬停的位置是否与他们一秒钟前悬停的位置相同。

<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')
    },
}

如果您想使用旧语法,请将 'this' 绑定到 setTimeout 函数

data() {
    return {
        hovered: false
    }
}

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

悬停 1 秒时显示,不再悬停时消失的实现。

<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;
    },
}