Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from input to vue's function

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?

like image 248
Grzegorz G. Avatar asked Aug 23 '17 12:08

Grzegorz G.


3 Answers

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);
  }
}
like image 63
thanksd Avatar answered Sep 21 '22 16:09

thanksd


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())
    }
}
like image 26
Shubham Patel Avatar answered Sep 19 '22 16:09

Shubham Patel


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
    }
  }
});
like image 45
bbsimonbb Avatar answered Sep 19 '22 16:09

bbsimonbb