Examples of Vue’s Clean Code

In the last part of this series we got Vue up and running, and addressed some of the questions beginners might ask.

Examples of Vue’s Clean Code

In this tutorial, we’re going to look a bit more into the various things Vue can do. But first, let’s talk about the view-centered nature of Vue.js.

Views, Models, and Binding

Vue (and most other view-oriented JavaScript frameworks) are built with a nearly singular focus on views. Let’s break down what that means.

1. All views are ultimately rendered somewhere. For web developers, that location is the DOM.

2. All views can be expressed as a series of nodes in a tree-like structure.

What does this mean, exactly?

If you’ve ever used HTML, then you already know what a tree structure looks like. And it just so happens that the tree structure works very well for representing view components, which is also one of the reasons HTML is so widely applicable to so many view possibilities.

3. There is a constantly connected symbiotic relationship between what happens in the view template code and what’s happening in the JavaScript Vue instance code.

Events, data, computed properties; all of these things share important context in a Vue instance.

Common Examples Where Vue Wins

Let’s take a look at two straight-forward use-cases where Vue can help you write cleaner, better code!

1. Live List Sorting

Sorting a list can be a tedious process if you are not using something like Vue. Of course, you can accomplish similar things with jQuery plugins, but let’s take a look at a simple sortable list.

The HTML:

<div id="app">
    <div class="sort-orders">
        <a v-for="sortkey in Object.keys(orderedListOptions)" v-on:click="sortOrder = sortkey" v-bind:class="{active: sortOrder == sortkey}">{{sortkey}}</a>
    </div>
    <ul>
        <li v-for="(item, index) in sort(sortOrder)" v-html="item" v-id="index">
    </ul>
</div>

The JavaScript:

let list = [
    "Michael Gary Scott",
	"Dwight Schrute",
	"Jim Halpert",
	"Pam Beesly-Halpert",
	"Darryl Philbin",
	"Erin Hannon",
	"Andy Bernard",
	"Phyllis Lapin-Vance",
	"Stanley Hudson",
  // ...
]

let vm = new Vue({
	data: {
		list: [],
		sortOrder: "Popularity",
	},
	created: function(){
		// simulating asynchronous loading of data
		setTimeout(() => {
			this.list = list;
		}, 1000)
	},
	computed: {
		orderedListOptions: function(){
			return {
				"Popularity": () => { return this.list },
				"A-Z": () => { return this.list.slice().sort() },
				"Z-A": () => { return this.list.slice().sort().reverse()},
			}
		},
	},
	methods: {
		sort: function(sortOrder){
			return this.orderedListOptions[sortOrder]()
		}
	},
	el: "#app"
})

With some basic styles to make things clear, this is what we get:

You’ll notice very quickly how straightforward this sorting process is. Of course, you may also notice that there is some duplication code in the view, but we’ll get to that a bit later.

The main bulk of the template code is the looping over the items themselves. The bulk of the JavaScript code is dedicated to the sorting of the list items. If you wanted another sorting method, you could easily add it to the orderedListOptions returned object.

Take particular note of the computed key, as well as the pieces of data we are keeping track of in the data object. We’re simulating the idea that the list is loaded from another source and brought in synchronously, but asynchronous data sources are perfectly usable as well:

let vm = new Vue({
  data: {
    list: []
  },
  created: function(){
        // simulating asynchronous loading of data
        setTimeout(() => {
            this.list = list;
        }, 1000)
    }
  // etc
})

With this addition, we have a few more important things to understand. First of all, the list key in the data is still important even though it is an empty array. This lets Vue know which properties it should watch for changes. Secondly, we are using an arrow function for the setTimeout simulation of asynchronous data loading. This allows us to use this in the parent context. You will likely use an arrow function in the future for a nested anonymous function in your Vue code, and access to this makes your code much easier to understand when updating data attributes.

2. Showing an Element Conditionally

A common use case for this example is the presence of a coupon code or banner that you want to hide if someone has already closed or used it before. One of the great things about Vue is that it works very well with other libraries and tools. If you want to use cookies, local storage, or any other browser-level persistence mechanism, nothing is stopping you from doing just that.

Let’s take a look at an example that uses localStorage to hide a banner once it’s been dismissed.

let vm = new Vue({
    data: {
        showBanner: !localStorage.getItem("hideBanner")
    },
    methods: {
        dismissBanner: function(){
            this.showBanner = false;
            localStorage.setItem("hideBanner", true);
        },
    },
    el: "#app"
})
<div id="app">
    <div class="banner" v-if="showBanner">
        <a class="remove" v-on:click="dismissBanner">&times;</a>
        <h4>Special Offer! 25% off.</h4>
    </div>
</div>

Here’s all that, wrapped up with some basic styles again, in CodePen:

We’re binding to the click event using Vue’s v-on directive. This allows us to listen to the click event, and use the methods object to respond to that click. We’re using localStorage to initialize the showBanner data attribute.

Wrapping up

With these examples you can start to see how Vue.js can help you replace some of your otherwise stringy JavaScript with more maintainable and separated code that is significantly easier to manage and understand.

In the next part of this series, we’ll cover how you can create your own components, and we’ll also discuss some of the most popular tools to extend Vue and make it even more powerful in your applications.