14 min read

In this article by Olga Filipova, the author of the book Learning Vue.js 2, explores the key concepts of Vue.js framework to understand all its behind the scenes. Also in this article, we will analyze all possible ways of installing Vue.js. We will also learn the ways of debugging and testing our applications.

(For more resources related to this topic, see here.)

So, in this article we are going to learn:

  • What is MVVM architecture paradigm and how does it apply to Vue.js
  • How to install, start, run, and debug Vue application

MVVM architectural pattern

Do you remember how to create the Vue instance? We were instantiating it calling new Vue({…}). You also remember that in the options we were passing the element on the page where this Vue instance should be bound and the data object that contained properties we wanted to bind to our view. The data object is our model and DOM element where Vue instance is bound is view.

Learning Vue.js 2

Classic View-Model representation where Vue instance binds one to another

In the meantime, our Vue instance is something that helps to bind our model to the View and vice-versa. Our application thus follows Model-View-ViewModel (MVVM) pattern where the Vue instance is a ViewModel.

Learning Vue.js 2

The simplified diagram of Model View ViewModel pattern

Our Model contains data and some business logic, our View is responsible for its representation. ViewModel handles data binding ensuring the data changed in the Model is immediately affecting the View layer and vice-versa.

Our Views thus become completely data-driven. ViewModel becomes responsible for the control of data flow, making data binding fully declarative for us.

Installing, using, and debugging a Vue.js application

In this section, we will analyze all possible ways of installing Vue.js. We will also create a skeleton for our. We will also learn the ways of debugging and testing our applications.

Installing Vue.js

There are a number of ways to install Vue.js. Starting from classic including the downloaded script into HTML within <script> tags, using tools like bower, npm, or Vue’s command-line interface (vue-cli) to bootstrap the whole application.

Let’s have a look at all these methods and choose our favorite. In all these examples we will just show a header on a page saying Learning Vue.js.

Standalone

Download the vue.js file. There are two versions, minified and developer version. The development version is here: https://vuejs.org/js/vue.js. The minified version is here: https://vuejs.org/js/vue.min.js.

If you are developing, make sure you use the development non-minified version of Vue. You will love nice tips and warnings on the console.

Then just include vue.js in the script tags:

<script src=“vue.js”></script>

Vue is registered in the global variable. You are ready to use it.

Our example will then look as simple as the following:

  <div id="app">
    <h1>{{ message }}</h1>
  </div>
  <script src="vue.js"></script>
  <script>
    var data = {
      message: "Learning Vue.js"
    };

    new Vue({
      el: "#app",
      data: data
    });
  </script>

CDN

Vue.js is available in the following CDN’s:

  • jsdelivr: https://cdn.jsdelivr.net/vue/1.0.25/vue.min.js
  • cdnjs: https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.25/vue.min.js
  • npmcdn: https://npmcdn.com/[email protected]/dist/vue.min.js

Just put the url in source in the script tag and you are ready to use Vue!

<script src=“ https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.25/vue.min.js”></script>

Beware so, the CDN version might not be synchronized with the latest available version of Vue.

Thus, the example will look like exactly the same as in the standalone version, but instead of using downloaded file in the <script> tags, we are using a CDN URL.

Bower

If you are already managing your application with bower and don’t want to use other tools, there’s also a bower distribution of Vue. Just call bower install:

# latest stable release
bower install vue

Our example will look exactly like the two previous examples, but it will include the file from the bower folder:

<script src=“bower_components/vue/dist/vue.js”></script>

CSP-compliant

CSP (content security policy) is a security standard that provides a set of rules that must be obeyed by the application in order to prevent security attacks. If you are developing applications for browsers, more likely you know pretty well about this policy!

For the environments that require CSP-compliant scripts, there’s a special version of Vue.js here: https://github.com/vuejs/vue/tree/csp/dist

Let’s do our example as a Chrome application to see the CSP compliant vue.js in action!

Start from creating a folder for our application example. The most important thing in a Chrome application is the manifest.json file which describes your application. Let’s create it. It should look like the following:

{
  "manifest_version": 2,
  "name": "Learning Vue.js",
  "version": "1.0",
  "minimum_chrome_version": "23",
  "icons": {
    "16": "icon_16.png",
    "128": "icon_128.png"
  },
  "app": {
    "background": {
      "scripts": ["main.js"]
    }
  }
}

The next step is to create our main.js file which will be the entry point for the Chrome application. The script should listen for the application launching and open a new window with given sizes. Let’s create a window of 500×300 size and open it with index.html:

chrome.app.runtime.onLaunched.addListener(function() {
  // Center the window on the screen.
  var screenWidth = screen.availWidth;
  var screenHeight = screen.availHeight;
  var width = 500;
  var height = 300;

  chrome.app.window.create("index.html", {
    id: "learningVueID",
    outerBounds: {
      width: width,
      height: height,
      left: Math.round((screenWidth-width)/2),
      top: Math.round((screenHeight-height)/2)
    }
  });
});

At this point the Chrome specific application magic is over and now we shall just create our index.html file that will do the same thing as in the previous examples. It will include the vue.js file and our script where we will initialize our Vue application:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js - CSP-compliant</title>
</head>
<body>
<div id="app">
    <h1>{{ message }}</h1>
</div>
<script src="assets/vue.js"></script>
<script src="assets/app.js"></script>
</body>
</html>

Download the CSP-compliant version of vue.js and add it to the assets folder.

Now let’s create the app.js file and add the code that we already wrote added several times:

var data = {
  message: "Learning Vue.js"
};

new Vue({
  el: "#app",
  data: data
});

Add it to the assets folder.

Do not forget to create two icons of 16 and 128 pixels and call them icon_16.png and icon_128.png.

Your code and structure in the end should look more or less like the following:

Learning Vue.js 2

Structure and code for the sample Chrome application using vue.js

And now the most important thing. Let’s check if it works! It is very very simple.

  1. Go to chrome://extensions/ url in your Chrome browser.
  2. Check Developer mode checkbox.
  3. Click on Load unpacked extension… and check the folder that we’ve just created.
  4. Your app will appear in the list! Now just open a new tab, click on apps, and check that your app is there. Click on it!

Learning Vue.js 2

Sample Chrome application using vue.js in the list of chrome apps

Congratulations! You have just created a Chrome application!

NPM

NPM installation method is recommended for large-scale applications. Just run npm install vue:

# latest stable release
npm install vue
# latest stable CSP-compliant release
npm install vue@csp

And then require it:

var Vue = require(“vue”);

Or, for ES2015 lovers:

import Vue from “vue”;

Our HTML in our example will look exactly like in the previous examples:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Vue.js - NPM Installation</title>
</head>
<body>
  <div id="app">
    <h1>{{ message }}</h1>
  </div>
  <script src="main.js"></script>
</body>
</html>

Now let’s create a script.js file that will look almost exactly the same as in standalone or CDN version with only difference that it will require vue.js:

var Vue = require("vue");
var data = {
  message: "Learning Vue.js"
};
new Vue({
  el: "#app",
  data: data
});

Let’s install vue and browserify in order to be able to compile our script.js into the main.js file:

npm install vue –-save-dev
npm install browserify –-save-dev

In the package.json file add also a script for build that will execute browserify on script.js transpiling it into main.js. So our package.json file will look like this:

{
  "name": "learningVue",
  "scripts": {
    "build": "browserify script.js -o main.js"
  },
  "version": "0.0.1",
  "devDependencies": {
    "browserify": "^13.0.1",
    "vue": "^1.0.25"
  }
}

Now run:

npm install
npm run build

And open index.html in the browser.

I have a friend that at this point would say something like: really? So many steps, installations, commands, explanations… Just to output some header? I’m out!

If you are also thinking this, wait. Yes, this is true, now we’ve done something really simple in a rather complex way, but if you stay with me a bit longer, you will see how complex things become easy to implement if we use the proper tools. Also, do not forget to check your Pomodoro timer, maybe it’s time to take a rest!

Vue-cli

Vue provides its own command line interface that allows bootstrapping single page applications using whatever workflows you want. It immediately provides hot reloading and structure for test driven environment. After installing vue-cli just run vue init <desired boilerplate> <project-name> and then just install and run!

# install vue-cli
$ npm install -g vue-cli
# create a new project
$ vue init webpack learn-vue
# install and run
$ cd learn-vue
$ npm install
$ npm run dev 

Now open your browser on localhost:8080. You just used vue-cli to scaffold your application. Let’s adapt it to our example. Open a source folder. In the src folder you will find an App.vue file. Do you remember we talked about Vue components that are like bricks from which you build your application? Do you remember that we were creating them and registering inside our main script file and I mentioned that we will learn to build components in more elegant way? Congratulations, you are looking at the component built in a fancy way!

Find the line that says import Hello from ‘./components/Hello’. This is exactly how the components are being reused inside other components. Have a look at the template at the top of the component file. At some point it contains the tag <hello></hello>. This is exactly where in our HTML file will appear the Hello component. Have a look at this component, it is in the src/components folder. As you can see, it contains a template with {{ msg }} and a script that exports data with defined msg. This is exactly the same what we were doing in our previous examples without using components. Let’s slightly modify the code to make it the same as in the previous examples. In the Hello.vue file change the msg in data object:

<script>
export default {
  data () {
    return {
   msg: “Learning Vue.js”
    }
  }
}
</script>

In the App.vue component remove everything from the template except the hello tag, so the template looks like this:

<template>
  <div id="app">
    <hello></hello>
  </div>
</template>

Now if you rerun the application you will see our example with beautiful styles we didn’t touch:

Learning Vue.js 2

vue application bootstrapped using vue-cli

Besides webpack boilerplate template you can use the following configurations with your vue-cli:

webpack-simple: A simple Webpack + vue-loader setup for quick prototyping.

browserify: A full-featured Browserify + vueify setup with hot-reload, linting and unit testing.

browserify-simple: A simple Browserify + vueify setup for quick prototyping.

simple: The simplest possible Vue setup in a single HTML file

Dev build

My dear reader, I can see your shining eyes and I can read your mind. Now that you know how to install and use Vue.js and how does it work, you definitely want to put your hands deeply into the core code and contribute!

I understand you. For this you need to use development version of Vue.js which you have to download from GitHub and compile yourself.

Let’s build our example with this development version vue. Create a new folder, for example, dev-build and copy all the files from the npm example to this folder.

Do not forget to copy the node_modules folder. You should cd into it and download files from GitHub to it, then run npm install and npm run build.

cd <APP-PATH>/node_modules
git clone https://github.com/vuejs/vue.git
cd vue
npm install
npm run build
Now build our example application:
cd <APP-PATH>
npm install
npm run build

Open index.html in the browser, you will see the usual Learning Vue.js header.

Let’s now try to change something in vue.js source! Go to the node_modules/vue/src folder. Open config.js file. The second line defines delimeters:

let delimiters = ['{{', '}}'] 

This defines the delimiters used in the html templates. The things inside these delimiters are recognized as a Vue data or as a JavaScript code. Let’s change them! Let’s replace “{{” and “}}” with double percentage signs! Go on and edit the file:

let delimiters = ['%%', '%%']

Now rebuild both Vue source and our application and refresh the browser. What do you see?

Learning Vue.js 2

After changing Vue source and replacing delimiters, {{}} delimeters do not work anymore!

The message inside {{}} is no longer recognized as data that we passed to Vue. In fact, it is being rendered as part of HTML.

Now go to the index.html file and replace our curly brackets delimiters with double percentage:

<div id="app">
  <h1>%% message %%</h1>
</div>

Rebuild our application and refresh the browser! What about now? You see how easy it is to change the framework’s code and to try out your changes. I’m sure you have plenty of ideas about how to improve or add some functionality to Vue.js. So change it, rebuild, test, deploy! Happy pull requests!

Debug Vue application

You can debug your Vue application the same way you debug any other web application. Use your developer tools, breakpoints, debugger statements, and so on. Vue also provides vue devtools so it gets easier to debug Vue applications. You can download and install it from the Chrome web store: https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd

After installing it, open, for example, our shopping list application. Open developer tools. You will see the Vue tab has automatically appeared:

Learning Vue.js 2

Vue devtools

In our case we only have one component—Root. As you can imagine, once we start working with components and having lots of them, they will all appear in the left part of the Vue devtools palette. Click on the Root component and inspect it. You’ll see all the data attached to this component. If you try to change something, for example, add a shopping list item, check or uncheck a checkbox, change the title, and so on, all these changes will be immediately propagated to the data in the Vue devtools. You will immediately see the changes on the right side of it. Let’s try, for example, to add shopping list item. Once you start typing, you see on the right how newItem changes accordingly:

Learning Vue.js 2

The changes in the models are immediately propagated to the Vue devtools data

When we start adding more components and introduce complexity to our Vue applications, the debugging will certainly become more fun!

Summary

In this article we have analyzed the behind the scenes of Vue.js. We learned how to install Vue.js. We also learned how to debug Vue application.

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here