VueJS Basics

VueJS: Managing User Input

In a previous tutorial we looked at how you can bind Vue data points to HTML attributes. In this tutorial we're going to look into how you can bind Vue data properties to user inputs such as a textbox.

We're going to build a small page that has a textbox and on the change event of this textbox it will update this on the page by using Vue data properties. Previously using jQuery you will need to add a change event to the textbox then in turn to grab this content and add the text into another element.

First lets add the HTML to the page.

<div id="app">
    <input type="text">
    <p></p>
</div>

To start with we'll compare this with the jQuery way of listening to a user input and printing the same text on the page.

$(document).ready(function(){
  $('input[type=text]').on('change', function(){
    $('p').html( $(this).val() );
  });  
});

Let's go through this code to see what's happening, first we check jQuery is ready to be used. Then we add a change event listener to the input[type=text], the function will be ran on each change of the textbox it will take this value and add it to the paragraph. This is a very simple example but you can see you need to write all this functionality yourself and you'll see the difference when compared to VueJS.

First we need to change the HTML and add a v-model directive to the textbox, this will bind the textbox to a data property in Vue. Then we simply need to output the data property by using the handlebar syntax to output the Vue data property.

<div id="app">
    <input v-model="message" type="text">

    <p>{{ message }}</p>
</div>

Now we just need to create a new Vue object with a data property of message.

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            message: 'Enter message'
        },
    })
</script>

That's all the code you need, now when type into the textbox you'll see the message appear on the page.

Demo

Back to top

View Demo

Members Download