How to bind the hoktey in one vue component(when leave this comp it will inactive)?

Author: liaodalin19903Created Nov 26, 2025Updated Nov 26, 2025

I have a Vue3 demo:

there is a requirement: I want to in User component I can use the hotkey, in other tabs(such as: Config) will not.

I tried to use onBeforeUnmount to unbind the hotkey in User component:

<template>
  User  
</template>

<script lang="ts" setup>

import hotkeys from 'hotkeys-js';
import { onMounted } from 'vue';


const handleF5 = function(event: KeyboardEvent) {
  event.preventDefault()
  alert('you pressed F5!')
};


onMounted(() => {
  hotkeys('F5', handleF5);
});


onBeforeUnmount(() => {
  hotkeys.unbind('F5', handleF5);
});



</script>
Image

but failed, in the Config I still can use the hotkey.

Image