In Vue app, detecting that a key press or mouse click happens

為{幸葍}努か 提交于 2021-01-27 11:54:13

问题


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

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

Thanks.


回答1:


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)

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


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

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

For example

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


来源:https://stackoverflow.com/questions/51887359/in-vue-app-detecting-that-a-key-press-or-mouse-click-happens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!