Vue范围:如何延迟@mouseover

时间:2017-08-02 13:38:33

标签: javascript scope vue.js delay mouseover

所以我想只有当用户在div上使用鼠标至少1秒时才有动作。内部模板:

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

内幕:

data() {
    return {
        hovered: false
    }
}

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

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

5 个答案:

答案 0 :(得分:3)

您是否尝试在setTimeout中使用箭头功能?它将保持this

data() {
    return {
        hovered: false
    }
}

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

实现在悬停 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;
    },
}

答案 3 :(得分:0)

我一直在解决仅在用户徘徊一段时间(以防止菜单闪烁)时选择列表中项目的问题

模板(pug):

.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 = ''
}

该方法是检查所徘徊的用户是否与前一秒所徘徊的用户相同。

答案 4 :(得分:0)

如果要使用旧语法,请将“ this”绑定到setTimeout函数

data() {
    return {
        hovered: false
    }
}

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