How to set keyup on whole page in Vue.js

Perhaps a better way to do this is with a Vue component. This would allow you to control when you listen to events by including or not including the component. Then you could attach event listeners to Nuxt using the no-ssr component.

Here is how you create the component:

<template>
  <div></div>
</template>
  
<script>
  export default {
    created() {
      const component = this;
      this.handler = function (e) {
        component.$emit('keyup', e);
      }
      window.addEventListener('keyup', this.handler);
    },
    beforeDestroy() {
      window.removeEventListener('keyup', this.handler);
    }
  }
</script>
  
<style lang="stylus" scoped>
  div {
    display: none;
  }
</style>

Then on the page you want to use that component you’d add this HTML:

<keyboard-events v-on:keyup="keyboardEvent"></keyboard-events>

And then you’ll have to add your event handler method:

methods: {
  keyboardEvent (e) {
    if (e.which === 13) {
      // run your code
    }
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)