How to set keyup on whole page in Vue.js

2019-06-15 02:31发布

Is it possible to set a v-on:keyup.enter on the whole page, not only for an input element in javascript framework Vue.js ?

标签: vue.js
2条回答
姐就是有狂的资本
2楼-- · 2019-06-15 03:26

Short answer is yes, but how depends on your context. If you are using vue-router as I am on a current project, you would want to add to the outer-most element you want that applied to. In my case I'm using the actual app.vue entry point's initial div element.

There is one catch that I believe is a hard requirement, the element has to be within the potentially focusable elements. The way I'm dealing with that is setting a -1 tabindex and just declaring my super-hotkeys (mostly for debug purposes right now) on the parent element in my app.

<template>
  <div
    id="app-main"
    tabindex="-1"
    @keyup.enter="doSomething"
  >
    <everything-else></everything-else>
  </div>
</template>

EDIT:

As a side note, I also added a touch of additional configuration to my vue-router to make sure the right element is focused when I transition pages. This allows the pageup/pagedown scrolling to already be in the right section based on the content area being the only scrollable section. You'd also have to add the tabindex="-1" to the app-content element as well.

router.afterEach(function (transition) {
  document.getElementById('app-content').focus();
});

and the basis of my app-content component:

<template>
  <div id="app-content" tabindex="-1">
    <router-view
      id="app-view"
      transition="app-view__transition"
      transition-mode="out-in"
    ></router-view>
  </div>
</template>
查看更多
女痞
3楼-- · 2019-06-15 03:30

Perhaps a better way to do this is with a Vue component. This would allow you to control when you listened to events by including or not including the component. This would also allow you to 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
    }
  }
}
查看更多
登录 后发表回答