Data Binding

The first principle of Vue we will learn about is how you can bind your application’s data to the DOM and update it dynamically.

Let’s look at a very simple example. First we create a barebones HTML page and pull in the unminified Vue source via CDN. Later we will install Vue using NPM, but for now this will work just fine.

// index.html
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>LearnVue Beginner Course | Lesson 1</title>
  </head>
  <body>
    <div>Hello Vue!</div>

    <script src="https://unpkg.com/vue@2.4.1/dist/vue.js"></script>
  </body>
</html>

Next, let’s make something happen on our page. Change the body of our page like so:

<body>
  <div id="app">
    <p>Hello {{ name }}!</p>
  </div>

  <script src="https://unpkg.com/vue@2.4.1/dist/vue.js"></script>

  <script>
    let app = new Vue({
      el: '#app',
      data: {
        name: 'Bob'
      }
    })
  </script>
</body>

And if you refresh the page our text will change to greet our good friend Bob. There are at least three important things happening here.

  • First we initialize our Vue instance in a script tag at the bottom of the page.
  • Then we tell it which HTML element we want to mount this instance on, using the id we gave to our div, by passing in el: '#app'.
  • Finally, we declare some data on this Vue instance with a variable called name and the value Bob, and render it to our page using the template syntax {{ name }}.

The great thing about this is that as our underlying data changes, the view will update to reflect the new state. How this is done will be explained in more detail later, but for now let’s take advantage of this by changing the data dynamically.

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

  <p>Hello {{ name }}!</p>
</div>

Note the introduction of our first Vue directive: v-model. This let’s us bind our new input field to our name variable that we defined on our Vue instance. Now if we refresh the page and type something into the input field, the change will be reflected on the page immediately.

In our next lesson we will look at a few more directives that we can use in our templates.

comments powered by Disqus