[Vuejs]-Vue.js Events: How to detect if key is pressed while the mouse is over a certain element?

1👍

I think you can use like this:

<div v-for="item in items"
    class="item"
    @mouseenter="isMouseOver = true"
    @mouseleave="isMouseOver = false"
    @keypress.shift="onMouseOverShift(item)"
/>

Then on the method onMouseOverShift you check if isMouseOver

0👍

I don’t think you can detect a keypress on a div, or at least not reliably. You best bet is probably to combine the mouse events with a global key watcher.

In Vue 3 composition API, this would look something like this:

In your component setup:

const hoveredItem = ref(null)
const shiftPressed = useShiftKeyWatcher()
const selectedItem = computed(() => shiftPressed.value ? hoveredItem.value : null)

In the template:

    <div v-for="item in items"
         class="item"
         @mouseenter="selectedItem = item"
         @mouseleave="selectedItem = null"
    >...</div>

Then the composable for useShiftKeyWatcher would look like:

import { ref, onMounted, onUnmounted } from "vue";

export function useShiftKeyWatcher() {
  const shiftPressed = ref(false);

  function checkKeyDown(event) {
    shiftPressed.value = event.key === "Shift";
  }

  function checkKeyUp(event) {
    shiftPressed.value &&= event.key !== "Shift";
  }

  onMounted(() => window.addEventListener("keydown", checkKeyDown));
  onMounted(() => window.addEventListener("keyup", checkKeyUp));
  onUnmounted(() => window.removeEventListener("keydown", checkKeyDown));
  onUnmounted(() => window.removeEventListener("keyup", checkKeyUp));

  return shiftPressed;
}

Here is a sandbox (you need to click into the preview area once to have key events go to the inner document)

Leave a comment