I have a button that performs certain actions when clicked with the mouse. I want the same method to be triggered when the keyboard's up arrow key is pressed.
<button @click="doSomething()"> PRESS ME </button> doSomething(){ console.log('clicked') }
So in this example, I want to console.log('clicked')
when the keyboard's up arrow is pressed. How can I do this?
P粉0314920812024-01-05 10:06:30
hope it helps you.
doSomething(){ console.log('clicked') } var buttonBtn = document.getElementById("btn"); buttonBtn.addEventListener("keyup", function(event) { event.preventDefault(); this.doSomething(); });
<button id="btn" @click="doSomething()"> PRESS ME </button>
P粉9940928732024-01-05 00:54:05
You can use onkeyrinkle
from vueuse
<template> <div> <button @click="doSomething">btn</button> </div> </template> <script setup> import { onKeyStroke } from '@vueuse/core'; const doSomething = () => { console.log('do something'); } onKeyStroke(['ArrowUp'], (e) => { doSomething(); }); </script>
stackblitz.com
does not support , so in this demo it is written with
setup()
renew
Pure js without libraries:
<template> <div> <button @click="doSomething"> btn </button> </div> </template> <script setup> import { onMounted, onBeforeUnmount } from 'vue'; const doSomething = () => { console.log('doSomething'); }; const userClickArrowUp = ({ code }) => { if (code === 'ArrowUp') { doSomething(); } }; onMounted(() => { document.addEventListener('keyup', userClickArrowUp, true); }) onBeforeUnmount(() => { document.removeEventListener('keyup', userClickArrowUp, true); }) </script>