Reputation: 679
I can add a watch property to a input form. But what if user presses a key. I want print the key press when the user is on the page.
$(document).keypress(function(event){
alert(String.fromCharCode(event.which));
});
But how do I add the check for keypresses in vue?
Upvotes: 2
Views: 5679
Reputation: 358
You have two options for registering the global event listener.
If you have another Vue Instance on your document's root you could use custom events.
Add to your main instance:
<body @keydown="this.$emit('onkeydown')">...</body>
And to your nested instance:
<my-component v-on:onkeydown="alert(String.fromCharCode(event.which));"></my-component>
This emits a global event which is caught by your nested instance. If you want to know more about custom events click here.
If there is no instance on your body
element you can just create an event listener on the document when your Vue instance is created (Example):
methods: {
onkeydown(e) {
alert(String.fromCharCode(event.which));
}
},
created() {
document.onkeydown = this.onkeydown;
}
Upvotes: 2
Reputation: 718
Try this
html
<div id="test">
<input v-on:keyup="say()">Say hi</input>
</div>
js
new Vue({
el: '#test',
methods: {
say: function (e) {
alert(e.keyCode)
}
}
})
Upvotes: 0