DEV Community

Michael Salaverry
Michael Salaverry

Posted on

Vue 3 Mouse and Keyboard event combo

I had trouble figuring out keyboard events in Vue, so I'm writing this for future reference

Edit in Vue SFC Playground

<script setup>
import { ref } from 'vue'
const hover = ref(false)
const key = ref('')
const events = ref([])
document.addEventListener('keydown', (e) => {
key.value = e.key;
events.value.push({ key: e.key, hover: hover.value.toString() })
})
</script>
<template>
<h3>
Hover (or not) the button below and type
</h3>
<button @mouseover="hover = true" @mouseleave="hover = false" class="hoverBtn">
Hover: {{hover}}
</button>
<table>
<th>key</th>
<th>during hover</th>
<tr v-for="ev in events">
<td>{{ev.key}}</td>
<td>{{ev.hover}}</td>
</tr>
</table>
</template>
<style>
.hoverBtn {
border: 1px solid black;
width: 10rem;
}
</style>

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay