Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set keyup on whole page in Vue.js

Tags:

vue.js

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 ?

like image 980
fvukovic Avatar asked Jul 17 '16 14:07

fvukovic


People also ask

How do I use Onkeyup in Vue JS?

The v-on:keyup directive is a Vue. js directive used to add an event listener to an button in the keyboard. First, we will create a div element with id as app and let's apply the v-on:keyup directive to the input element. Further, we can execute a function when we press the associated key.

How do I add event listeners to Vue?

To add an event listener to a component using the v-on directive with Vue. js, we should add the native modifier. to set the add the native modifier to @click and set it to buttonClickHandler . Then buttonClickHandler will run when we click on the router-link component.

What is click stop Vue?

prevent is a modifier for v-on:click . Another handy modifier is . self , which tells Vue to only evaluate v-on:click if the element itself is clicked, as opposed to one of its children. For example, Vue only calls the below v-on:click handler when you click on the outer div , not the inner div .


1 Answers

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     }   } } 
like image 76
James Avatar answered Oct 04 '22 04:10

James