Header Ads

Learn Vue.js Step By Step: Basic Data Binding

Do you find Vue quite overwhelming or you're simply want to learn Vue? Well, don't worry, this Vue tutorial series will try to cover those two reasons. Let's get started!

Installation

You can pull Vue through NPM npm install vue, but throughout this series we'll make things more simple as possible. So we'll just grab the recommended CDN version of Vue (https://unpkg.com/vue).

The Code

<!DOCTYPE html>
<html>
<head>
<title>Learn Vue Step By Step: Basic Data Binding</title>
</head>
<body>
    <div id="app">
        <input type="text" id="name" v-model="name">
        <p>Hi!, my name is {{ name }}.</p>
    </div>

    <script src="https://unpkg.com/vue"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
              name: 'John Doe'
            }
        })
    </script>
</body>
</html>
As you can see, when you open the above snippet in the browser, you'll notice that when you change the input box, the sentence below also change. That's one Vue's feature that makes it so powerful, with just few lines of codes you were able to bind data into the DOM.

The Explanation

Vue needs to know the root element where it should be working. In this case we're telling Vue to only mind elements inside the div with an id of app, by assigning the div id to the el property. So, basically any elements outside that div, Vue won't work.
<div id="app"></div>

When dealing with form elements such as input, you have to use the v-model directive, if you want to create a two-way data binding between the input and the data property. Remember that you have to define what ever value of your v-model into the data property object.
<input type="text" id="name" v-model="name">

This is how you echo out the data in Vue:
<p>Hi!, my name is {{ name }}.</p>

The code below simply instantiating the Vue class. The el property determines the root element of your application. On the other hand, the data property accepts an object that can be use in the v-model directive for two-way data binding.
<script>
    new Vue({
        el: '#app',
        data: {
          name: 'John Doe'
       }
    })
</script>

Next: List Rendering


No comments