VueJS: @keydown, @keyup, and this.$refs works with input, but not with md-textarea

ITWitch picture ITWitch · Mar 16, 2017 · Viewed 40.7k times · Source

I have successfully completed a basic speed typing game using vue.js. For the "typing box", I used <input>, and everything worked fine. However, when I added more levels to my game, with longer sentences for the user to type, I have identified the need to change my <input> element into <md-textarea> - a vue.js component.

THE PROBLEM:

The following attributes that were working fine with <input> won't work as expected with <md-textarea>:

  • @keyup="checkAnswer()"
  • @keydown="keymonitor"
  • @keydown.ctrl.86="noPaste" (prevents paste via Ctrl+V)
  • @keydown.shift.45="noPaste" (prevents paste via Shift+Insert)
  • ref="typeBox" (allows focusing on the element via this.$refs.typeBox[0].focus())

Please refer to the codes below.

Am I missing anything? Please help me debug this. Thank you.

NOTE: I know it throws an error here in SO snippet feature, but that error does not exist in my development environment.

Answer

thanksd picture thanksd · Mar 16, 2017

You can bind functions to the native events of the root element of a component by using the .native modifier. See the documentation here.

In your case, you can add native event handlers to the <md-textarea> component like so:

<md-textarea 
  id="typeBox" 
  autocomplete="off" 
  placeholder="Type here..." 
  ref="typeBox" 
  v-model="answer" 
  @keydown.native="keymonitor" 
  @keydown.native.ctrl.86="noPaste" 
  @keydown.native.shift.45="noPaste"
></md-textarea>