To add a keyboard listener in Vue, use the mounted()
function.
Example:
vue<template> <button @click = 'show'>Click or press Enter</button> </template> <script> export default { mounted(){ window.addEventListener('keyup', this.show) }, methods: { show(e){ if(e.key === 'Enter') alert('Enter pressed') if(!e.key) alert('Button clicked') } } } </script>
Additionally, you can use the unmounted()
function to remove the listener:
javascriptunmounted(){ window.removeEventListener('keyup', this.show) }
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.