3

I am trying to implement common chat app on Vue.js.

window.onload = function () {
  new Vue({
    el: '#vue-chat',
    data: {
      body: ''
    },
    methods: {
      fooMethod: function () {
        alert('foo');
      },
      barMethod: function () {
        alert('bar');
      }  
    }
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.3/vue.js"></script>
<div id="vue-chat">
  <ul class="comments">
    <li></li>
  </ul>

  <input type="text" v-model="body" @keyup.enter="fooMethod">
</div>

and i want to call barMethod when users press enter key and shift key at the same time.

I read docs however I could not find the way. Thank you for reading!

2 Answers 2

3

With the shift key and other modifier keys you can see if they were pressed through the event object.

I'd use a single method with @keyup.enter and then decide to which method to call based on the event's shiftKey value.

new Vue({
  el: '#app',
  data: {
    message: 'Hi',
  },
  methods: {
    action(event) {
      if (event.shiftKey) {
        this.shiftKeyPressed()
      } else {
        this.shiftKeyNotPressed()
      }
    },
    shiftKeyPressed() {
      console.log('Shift key was pressed.')
    },
    shiftKeyNotPressed() {
      console.log('Shift key was NOT pressed.')
    },
  }
})

Here's a quick demo: https://jsfiddle.net/bj75cyd3/

Sign up to request clarification or add additional context in comments.

Comments

0

There is no trivial way to do what you want.

You can't reach your goal through modifiers; you have to drop the .enter modifier and deal with the keyup event, as well as the keydown event.

  <input type="text" v-model="body" @keyup="keyUp" @keydown="keyDown">

There are a short answer and a long answer suggesting how to track multiple keys pressed at once in JavaScript.

Based on the answers linked above, we can build the basis of our Vue solution:

data: {
    shiftPressed: false
},
methods: {
    keyDown: function (event) {
        if (event.keyCode === 16) {
            this.shiftPressed = true
        }
    },
    keyUp: function(event) {
        if (event.keyCode === 16) {
            this.shiftPressed = false
        }
        if (this.shiftPressed && (event.keyCode === 13)) {
            this.shiftPressed = false   // avoid double trigger
            this.fooMethod()
        }
    }
}

1 Comment

This is definitely the case for non-modifier keys, but with keys like shift, alt, meta, ctrl they're included in the keypress event. So they can technically do like keyup.enter="foo" and the event will let you know if shift if pressed through event.shiftKey.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.