Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get input value on keyup Vuejs 2

Tags:

vue.js

vuejs2

I'm trying to get the input value on keyup using Vuejs 2 but always get an empty result like the data. Please see code below.

HTML:

<input type="email" @keyup="this.$data.email= $event.target.value" class="form-control" id="email" placeholder="Username (your work email)">
<button type="button" class="btn btn-primary btn-block inactive" @click="submit">Log in</button>

Script:

data () {
  return {
    email: '',
  }
},
methods: {
  submit () {
    alert(this.$data.email)
  }
}
like image 658
claudios Avatar asked Jul 26 '17 15:07

claudios


People also ask

How do I get input data from Vue?

To get an input value in Vue, we can use the v-model directive to set up a two-way binding between the value and a variable. Every time the user changes the text in the input field, the text variable will be updated automatically. We can then use this variable to perform an action or display information.

What is V on Keyup?

The v-on:keyup directive is a Vue. js directive used to add an event listener to an button in the keyboard. First, we will create a div element with id as app and let's apply the v-on:keyup directive to the input element. Further, we can execute a function when we press the associated key.

What are key modifiers in Vuejs?

There are several other key modifiers built into Vue. js, such as tab, delete, esc and space, just to mention a few. And, if you need other keys than the available key modifiers, then you can use a number as the modifier instead. This number represents the character code, exactly as in vanilla JavaScript.

What is V-model Vue?

Vue v-model is a directive that creates a two-way data binding between a value in our template and a value in our data properties. A common use case for using v-model is when designing forms and inputs. We can use it to have our DOM input elements be able to modify the data in our Vue instance.


1 Answers

You need to reference email (not this.$data.email):

<input type="email" @keyup="email = $event.target.value" class="form-control" id="email" placeholder="Username (your work email)">

But also, why not use v-model to bind email to the input?

new Vue({
  el: '#app',
  data () {
    return {
      email: '',
    }
  },
  methods: {
    submit () {
      alert(this.email)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <input type="email" v-model="email" class="form-control" id="email" placeholder="Username (your work email)">
  <button type="button" class="btn btn-primary btn-block inactive" @click="submit">Log in</button>
</div>
like image 68
thanksd Avatar answered Sep 25 '22 12:09

thanksd