0

Using Vue, I am trying to make a button change its behavior when the Shift key is held. It was pretty easy to change the behavior of the click event as such:

@click.exact="goForward"
@click.shift="goBackward"

However, I am struggling with changing the text of the button to reflect this behavior. The default text is Forward, and I am trying to change it to Backward when the Shift key is being held down.

I tried to use @mouseover.shift but it's not good enough, because it does not capture the case of mouse enters the button, then user holds shift

Kfir Eichenblat
  • 449
  • 2
  • 8
  • 27

1 Answers1

1

You can use the vue-keypress package:

<template>
  <div>
    ...
    <button>{{ buttonText }}</button>
    ...
    <Keypress key-event="keydown" :key-code="16" @success="buttonText = 'Backward'" />
    <Keypress key-event="keyup" :key-code="16" @success="buttonText = 'Forward'" />
  </div>
</template>

<script>
export default
{
  data: () => ({
    buttonText: 'Forward',
  }),
}
</script>
IVO GELOV
  • 13,496
  • 1
  • 17
  • 26
  • Looks good, I'll give it a go. I was really hoping there'd be a way to do it without external packages though – Kfir Eichenblat Oct 10 '20 at 20:59
  • 1
    IF you do not want to bring external package for this work - you can simply attach a `keyup` and `keydown` event handlers to `document` which can update a variable inside the root Vue instance which you can then access by `$root.ShiftActive` – IVO GELOV Oct 11 '20 at 16:02