Anam Anam - 4 years ago 320
Javascript Question

Listening for multiple keyup events in Vue 2.0

I am developing a messaging app and i need to list multiple event listeners for the message box (textarea). When the user press enter (

@keyup.enter
), the message will send automatically. However, we want to allow user to add line break if they want to organise the message. So, we add
@keyup.shift.enter
(SHIFT + ENTER) listener to do that. The problem is when user press
SHIFT + ENTER
it call both
@keyup.enter
and
@keyup.shift.enter
. Is there anyway to prevent
@keyup.enter
event?

<textarea
v-model="message"
@keyup="typing"
@keyup.shift.enter="newLine"
@keyup.enter="sendMessage"
></textarea>

Answer Source

One way to do this can be not use @keyup.shift.enter and inside the vent handler of @keyup.enter you check whether shift is also pressed, if yes, than call newLine otherwise sendMessage, like following:

methods: {
  typing () {
     console.log("typing")
  },
  newLine () {
    console.log("newLine")
  },
  sendMessage (event) {
    if(event.shiftKey){       
         console.log("newLine")
     } else {
         console.log("sendMessage")
     }
  }    
}

See working fiddle here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download