Reputation: 163
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!
Upvotes: 3
Views: 10649
Reputation: 32921
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/
Upvotes: 3
Reputation: 20492
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()
}
}
}
Upvotes: 0