Vue: How to change a button's text while a keyboard modifier is held?

327 views Asked by At

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

1

There are 1 answers

2
IVO GELOV On BEST ANSWER

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>