Getting Started with Vue.js

Vue Basics

Vue provides a very succinct and clean API to build out our applications.

The Vue Instance

Every Vue application starts with a Vue instance. Vue instances consist of three main parts:

  • el: This will be the CSS selector for the area you want Vue to attach itself to
  • data: These will be all your data variables needed for your app
  • methods: All the functions and functionality your app needs

The syntax for creating a Vue instance looks like so:

var app = new Vue({
    el: '#app',

    data: {
        myVariableOne: 'something',
        myVariableTwo: 'something else'
    },

    methods: {
        celebrate: function() {
            alert('we are celebrating!');
        }
    }
});

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

<div id="app">
    <h1 class="title">{{ myTitle }}</h1>
</div>
var app = new Vue({
    el: '#app',

    data: {
        myTitle: 'Hello World!'
    }
});

Binding Attributes

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'
    }
});

Handling Events

Listening for and acting on events is JavaScript's bread and butter. This is how we can get our dull HTML applications to come to life and have that interactivity.

Listening for events is an easy task in Vue using the v-on directive. We can listen for any of the native HTML DOM events in addition to custom ones we can make ourselves.

Some examples of this syntax would be:

<a v-on:click="incrementCounter">Increment Button</a>

<form v-on:submit="processForm"></form>

<input @keyup="updateText">

Shorthand

The v-on syntax can also be simplified with the @ symbol.

<a v-on:click="incrementCounter">Increment Button</a>

<!-- shorthand -->
<a @click="incrementCounter">Increment Button</a>