How to customize the keyboard on the whole page in Vue.js

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

+11
source share
2 answers

The short answer is yes, but it depends on your context. If you are using vue-router, since I am in the current project, you need to add to the external element that you want to apply. In my case, I am using the actual start element of the entry entry.vue element.

There is one catch, which, it seems to me, is a strict requirement, the element must be inside potentially oriented elements. The way I do this is to set -1 to tabindex and just declare my super-hot keys (mainly for debugging purposes right now) in the parent element in my application.

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

EDIT:

As an additional note, I also added some additional settings for my vue-router, to make sure that the right element is focused when going to pages. This allows you to scroll the page / pagedown already in the desired section based on the content area, which is the only scrollable section. You also need to add tabindex = "- 1" to the app-content element.

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

and the basic component of my application:

 <template> <div id="app-content" tabindex="-1"> <router-view id="app-view" transition="app-view__transition" transition-mode="out-in" ></router-view> </div> </template> 
+11
source share

Perhaps the best way to do this is with the Vue component. This allows you to control when you listen to events by enabling or not enabling the component. It will also allow you to connect event listeners to Nuxt using the no-ssr component .

This 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, you add this HTML code:

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

And then you have to add an event handler method:

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

All Articles