在 Vue 应用程序中,检测到按键或鼠标点击发生 [英] In Vue app, detecting that a key press or mouse click happens

查看:43
本文介绍了在 Vue 应用程序中,检测到按键或鼠标点击发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Vue 应用程序中,我有一个地方可以设置计时器.如果用户按任意键或点击浏览器窗口中的任意位置,我想中断计时器.

In my Vue app, I have a place where I'm setting a timer. I'd like to interrupt the timer if the user presses any key or clicks anywhere in the browser window.

我不想阻止他们点击的任何事情发生.我只想在它发生时收到回调.

I do not want to stop whatever they clicked from happening. I just want to get a callback whenever it does.

我可以只在每个处理程序中放置一个函数调用,但这既乏味、草率又不易于维护.

I could just put a function call in every handler, but that is both tedious, sloppy, and not very maintainable.

这就是我想要实现的目标:

This is what I'm trying to achieve:

let timerId;
const startTheTimer = () => {
  timerId = setTimeout(() => { 
    somestuff();
    timerId = undefined;
  }, 10000);
}

// Called whenever any mouse click or keyboard event happens
const userDidSomething = () => {
  if (timerId) {
    clearTimeout(timerId);
    timerId = undefined;
  }
}

那么,我的问题是,如何调用 userDidSomething() 函数?

So, my question is, how do I get the function userDidSomething() to be called?

谢谢.

推荐答案

您的问题似乎与 Vue 没有太大关系.您只需要将事件侦听器附加到 document.例如

Your question doesn't seem to have much to do with Vue. You'd just need to attach an event listener to document. For example

document.addEventListener('click', userDidSomething)
document.addEventListener('keydown', userDidSomething)

注意:任何被捕获并调用了 stopPropagation() 的事件都不会到达 document.

Note: Any event that is caught and has stopPropagation() called will not reach the document.

如果您的计时器设置在组件中,您可能应该在组件的 mounted 生命周期钩子中执行所有这些操作.

If your timer is set within a component, you should probably do all this in your component's mounted lifecycle hook.

清除超时并删除 beforeDestroy 挂钩中的侦听器也是一个好主意.

It would also be a good idea to clear the timeouts and remove the listeners in the beforeDestroy hook.

例如

export default {
  data () {
    return {
      timerId: null
    }
  },
  methods: {
    startTimer () {
      this.timerId = setTimeout(...)
    },
    clearTimer () {
      clearTimeout(this.timerId)
    }
  },
  mounted () {
    this.startTimer() // assuming you want to start the timer on mount
    document.addEventListener('click', this.clearTimer)
    document.addEventListener('keydown', this.clearTimer)
  },
  beforeDestroy () {
    this.clearTimer()
    document.removeEventListener('click', this.clearTimer)
    document.removeEventListener('keydown', this.clearTimer)
  }
}

这篇关于在 Vue 应用程序中,检测到按键或鼠标点击发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆