javascript - 如何仅在使用 VueJS 将鼠标悬停在 div 上时增加数字?

标签 javascript vue.js mouseevent

我想创建一个复活节彩蛋,如果访问者将鼠标放在文本 block 上五秒钟,就会触发该彩蛋。

这是我的代码:

<template>
 <!-- Some code -->
<div class="side-message" @mouseover="ee" @mouseleave="reset">
  <h1 v-if="easter" :class="easter ? 'ee' : ''">[ HYPE INTENSIFIES ]</h1>
  <p v-else v-html="replace($t('contact.intro'))"></p>
</div>
<!-- Rest of code -->
</template>

<script>
export default {
  data () {
    return {
      easter: false,
      seconds: 0,
      inside: false
    }
  },

  methods: {
    ee () {
      setInterval(() => {
        this.seconds += 1
      }, 1000)
      if (this.seconds >= 5 {
        this.easter = true
      }
      this.inside = true
    },

    reset () {
      this.seconds = 0
      this.inside = false
    }
  }
}

我的问题是 this.seconds 不会根据 Vue 控制台增加,我不太明白为什么。另外,this.inside 也保持为 false。但如果我想在函数内部设置一个 console.log() ,它将毫无问题地触发。

我错过了什么?

提前谢谢

最佳答案

您的代码存在一些语法错误和一些薄弱的逻辑。

尝试以下操作...

<template>
 <!-- Some code -->
<div class="side-message" @mouseover="ee" @mouseleave="reset">
  <h1 v-if="easter" :class="easter ? 'ee' : ''">[ HYPE INTENSIFIES ]</h1>
  <p v-else v-html="replace($t('contact.intro'))"></p>
</div>
<!-- Rest of code -->
</template>

<script>
export default {
  data () {
    return {
      timeInterval: null,  // to control the timeout alarm so that it doesn't run forever even when not needed
      easter: false,
      seconds: 0,
      inside: false
    }
  },

  methods: {

    // will stop incrementing seconds (if already running)
    stopTimer(){
        if (this.timeInterval)
          clearInterval(this.timeInterval);  
    },

    ee () {
      this.stopTimer();

      this.timeInterval = setInterval(() => {
        this.seconds += 1;
        if (this.seconds >= 5) {
            this.easter = true;
            this.stopTimer();
        }
      }, 1000);

      this.inside = true;
    },

    reset () {
      this.seconds = 0;
      this.inside = false;
      this.stopTimer();
    }
  }
}

关于javascript - 如何仅在使用 VueJS 将鼠标悬停在 div 上时增加数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53426917/

相关文章:

Vue.js - 无需编译模板的友好语法

javascript - 这个 MouseEvent 属性从何而来?

python - 有没有办法从 Windows 单击调用 python?

javascript - 使用 javascript 获取选择的开始和结束

vue.js - 无法使用异步方法在.vue文件中设置断点

javascript - 如何渲染数组以选择选项 vue.js

python - 用python编写的鼠标运动跟踪程序

javascript - 如何使用struts2框架在javascript中调用action类中的方法?

Javascript正则表达式,仅替换一次

javascript - Knockoutjs View 模型结构