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)
}
}
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.
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.
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.
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.
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>
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