Passing data from input to vue's function
You could either use v-model
to bind a data property to the input, and simply reference that in your method (see this fiddle):
<input v-model="message" @keyup.enter="addMessage()"/>
methods: {
addMessage() {
this.messages.push(this.message);
}
}
Or, you can use the special inline $event
property, which gives you a reference to the target element's value (see this fiddle):
<input @keyup.enter="addMessage($event)"/>
methods: {
addMessage(e) {
this.messages.push(e.target.value);
}
}
You also don't need to explicitly pass the $event
param to the @
handler. You can just pass the handler the method name and the first argument will still be the value of $event
.
Like so:
<input @keyup.enter="addMessage"/>
methods: {
addMessage(e) { // e is the value of $event
this.messages.push(e.target.value);
}
}
Solution 1: Using v-model(Preferred)
HTML
<input id="txtName" @keyup.enter="addMessage" v-model="txtInput" type="text">
VueJS
data: {
txtInput: ''
},
methods: {
addMessage(){
console.log(this.txtInput)
}
}
Solution 2: Using jQuery
HTML
<input id="txtName" @keyup.enter="addMessage('txtName')" type="text">
import jQuery using import $ from jquery
(webpack2 example)
VueJS
methods: {
addMessage(id){
console.log($('#txtName').val())
}
}
Here is your example corrected to work. Just a couple of syntax errors, plus the handy fact that if you don't specify arguments in the onkeyup, you get the event, which is what you want.
markup
<div id='ctr'>
{{message}}
<input id="txtName" v-on:keyup.enter="addMessage" type="text">
</div>
js
var vm = new Vue({
el : '#ctr',
data : {message: 'hello cobber'},
methods: {
addMessage: function(event){
debugger;
alert(event.target.value)
//stuff
}
}
});