How to Get Up and Running With Vue

In the introductory post for this series we spoke a little about how web designers can benefit by using Vue. In this tutorial we’ll learn how to get Vue up and running, whilst answering some initial questions you may have.

How to Get Up and Running With Vue

How to Add Vue to Your Project

Vue is just JavaScript, which means you can load it by including a script tag in your HTML document. Vue’s site recommends using a CDN like https://cdn.jsdelivr.net/npm/vue to be sure of getting the latest version. You can also use other version-specific links like https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js.

<script src="https://cdn.jsdelivr.net/npm/vue" type="application/javascript"></script>

Note: If you are creating a production app, it is recommended that you use a package controller like yarn to manage all of your dependencies, and deploy to CDN-powered locations. This is particularly important if you want to build Vue into your JavaScript package, for example using something like Webpack.

Understanding Markup and Templates

When creating a Vue “instance”, you can use the el option in the configuration object to connect your instance to the DOM. The el option should be either an element or a CSS selector string. This element can also contain template code. So, in your page’s HTML, you could have something like this:

<div id="app">
  <h1>{{title}}</h1>
  <p>{{content}}</p>
</div>

And then in your JavaScript, you would have something like this:

var app = new Vue({
  el: "#app",
  data: {
    title: "Threat Level Midnight",
    content: "AGENT MICHAEL SCARN, ruggedly handsome without even trying, relaxes at his desk, feet up, reviewing a case file. His gunrests next to his FBI badge, which glints in the office’sbuzzing florescent light. Dressed in a suit, he’s loosened his tie and undone some of the buttons, revealing his hairy chest."
  },

})

Again, note that the "#app" string is referring to the div in your HTML. Vue will replace the inner contents of that div with the result of Vue’s rendering step.

How to Get Up and Running With Vue

What Vue Does in the Background

We’ve established that Vue allows us to separate our view from our data. Some logic may be performed in the view itself, but we’re able to avoid the following patterns that lead to poor code or an incorrect state:

  • Storing/reading data in the DOM
  • Updating the DOM using direct DOM manipulation and modification rather than template rendering
  • Using procedural methods to evaluate state in disjointed ways that often lead to a DOM representation that doesn’t match the intended state

So how does this work?

Vue allows you to set information in the data option. Any key-value pair passed inside of this object will be observed for changes, and anything depending on that piece of data will be re-rendered when the data changes.

What this means essentially is that the data object is reactive. If you use JavaScript’s built-in data manipulation methods, the change will trigger Vue’s rendering engine to do its magic.

For example, if your data object is set up like this:

var vm = new Vue({
  el: "#app",
  data: {
    items: []
  }
});

With this template code:

<div id="app">
  <div v-for="item in items">{{item.text}}</div>
</div>

And later you add some items, like this:

vm.items = [{text: "Diversity Day"}, {text: "Beach Trip"}]

The template would automatically re-render, iterating (looping over) the items being set.

Important Caveat for Reactivity

As the JavaScript feature that allows Vue to watch the data object (object getters and setters) doesn’t provide information when new keys are added or existing keys are removed, adding and removing keys doesn’t trigger any re-rendering. So, in the same example above, if the initial data object is empty (items: [] isn’t present):

var vm = new Vue({
    el: "#app",
	data: {}
})

Any change to vm.items won’t trigger a rerendering. From the Vue documentation:

“Vue does not allow dynamically adding new root-level reactive properties to an already created instance.”

Additionally, it’s important to note that when adding items to an array using the syntax array[index] = 'new value', re-rendering will not be triggered. Instead, you should use splice, or Vue’s Vue.set method, which is beyond the scope of this article. View the list of caveats in the Vue documentation.

Working Alongside jQuery and Other Libraries

Vue does not conflict with jQuery, Underscore, or any other popular JavaScript utility library. However, you should think twice about trying to use Vue alongside another JavaScript framework like React.

It’s likely that you don’t necessarily need jQuery in addition to Vue, but it’s possible that you want to use it in other areas of your application that aren’t being rendered by Vue.

Vue also provides “hooks” to integrate with other libraries, for example, to perform animations.

Using Babel or Another Transpiler

Vue does not require Babel for you to be productive with it. However, Babel will allow you to use some of JavaScript’s forefront spec features, like template strings and more sophisticated array manipulation techniques.

Vue does not require any special build systems, which makes it very accessible to design-oriented developers who are used to writing small amounts of JavaScript, while still being powerful enough to be integrated into more complex build systems and full single-page applications.

Using Vue Multiple Times on the Same Page

Not only can you have multiple Vue instances on the same page, but you can even reference the same underlying data object on the same page. For example, in our previous data list example, if our JavaScript looked like this:

var sharedObject = {
    items: []
}

let vm = new Vue({
	el: "#app",
	data: sharedObject
})

vm.items = [{text: "Diversity Day"}, {text: "Beach Trip"}]

The result of using this template would be the same as our previous example:

<div id="app">
    <div v-for="item in items">{{item.text}}</div>
</div>

However, we can also add a second instance of Vue that references the same underlying data representation like this:

var vm2 = new Vue({
    el: "#app2",
	data: sharedObject
})

We could then show, for example, the count of items in the list:

<div id="app2">
    <div>{{items.length}}</div>
</div>

Of course, this may not be the desired behavior. You may want to create two components that aren’t tied to the same underlying object, and that will work without issue.

If you want to create two separate instances that start with the same underlying object, you can use the Object.assign method to create new copies of the same object.

let vm2 = new Vue({
    el: "#app2",
	data: Object.assign({}, sharedObject)
})

Conclusion

Vue is an excellent choice for developers who want a lightweight framework that is easy to adopt, but anticipate needing a more robust framework in the future. Vue will scale with your needs. Understanding how to use Vue in various scenarios (and having an idea of what’s happening under the surface) will provide you with a very powerful toolset that you can be productive with from day one.

In the next tutorial we’ll cover more of the unique value that Vue provides by looking at some examples of Vue’s clean code. See you there!