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 ?
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.
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.
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 .
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 } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With