Vue allows us to simply and declaratively write out our HTML. Vue will look at the HTML we've written and look for spots where it needs to work for us. We can tell Vue where to inject content or change our DOM by using a few methods like:

  • interpolation: injecting a piece of content into our template
  • directives: attach directives to HTML elements to tell Vue how to change it
  • event bindings: tell Vue what HTML DOM events to listen to and how to react

Interpolation

Once we have our Vue instance, data, and methods, we'll need to be able to show that information in our HTML templates. To do that, interpolation (injecting a piece of content into another) will be used.

To use interpolation, use the double brackets with your variable: {{ myVariable }}

Table of Contents

    <div id="app">
        <h1 class="title">{{ myTitle }}</h1>
    </div>
    var app = new Vue({
        el: '#app',
    
        data: {
            myTitle: 'Hello World!'
        }
    });

    Directives

    While interpolation works well for binding to text spots, we often need to bind information to an HTML attribute like src or title or href. We can use what's called directives to affect our HTML.

    To bind to an attribute, use: v-bind:src or the shorthand :src

    <div id="app">
        <img width="300" height="300" v-bind:src="avatar">
    
        <!-- or with the shorthand -->
        <img width="300" height="300" :src="avatar">
    </div>

    Personally, I like adding in Vue attributes at the end of an element, after all the main HTML elements are written out. This helps for organization and let's me know where to look for the directives.

    var app = new Vue({
        el: '#app',
    
        data: {
            avatar: 'https://pbs.twimg.com/profile_images/850147482117865472/O28qQSrN_400x400.jpg'
        }
    });

    Some other popular directives are:

    • v-if
    • v-show
    • v-hide

    Event Bindings

    We can tell Vue what events to listen for and react to by using the v-on syntax.

    To listen for an event on an element, use: v-on:click or the shorthand @click

    You can listen for any of the HTML DOM events

    <div id="app">
        <a class="button is-info" @click="celebrate">
            Do the Celebration!
        </a>
        </div>
    var app = new Vue({
        el: '#app',
        data: {
        },
        methods: {
            celebrate: function() {
                alert(`${this.name} is celebrating!`);
            }
        }
    });

    Chris Sevilleja

    173 posts

    Co-founder of Scotch.io. Slapping the keyboard until something good happens.