I want to pass data from an input:
<input
id="txtName"
type="text"
v-on:keyup.enter="addMessage(/* THIS FIELD VALUE */)"
/>
to a method:
methods: {
addMessage(name) {
//stuff
}
}
I tried using this
or this.value
as a parameter but it is not working.
How should I solve this?
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.
<div id='ctr'>
{{message}}
<input id="txtName" v-on:keyup.enter="addMessage" type="text">
</div>
var vm = new Vue({
el : '#ctr',
data : {message: 'hello cobber'},
methods: {
addMessage: function(event){
debugger;
alert(event.target.value)
//stuff
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With