An introduction to Vue.js part 1 of 3
A long time ago, I briefly dabbled in Ember.js. It was my very first exposure to the world of javascript frameworks, and I was quite uncomfortable with it, finding it difficult to relate the concepts back to my previous experience working with Ruby on Rails. I had also heard about AngularJS and walked through the first 3 or 4 pages of their getting started documentation, finding it similarly difficult to wrap my brain around the paradigm of front end JavaScript frameworks. These days I’m regularly elbow deep in either AngularJS or Angular as it is the primary tool my current client uses for front end development. At the time I started this project, I very much felt like I was thrown in the deep end, but the combination of learning because my job depended on it and having really great coworkers as resources to help me understand the frontend JavaScript framework paradigm, I managed to come to a comfortable, albeit general, understanding of how these things work.
I once saw the joke on Twitter that went something like ‘It has been 0 days since the last new JavaScript framework was released.’ Though I laughed at the time, I didn’t really appreciate the joke until I did a search of what JS frameworks were out there. There were so many more than I realized. So I decided I would start a challenge; give 10 hours a month to playing with a new JavaScript framework. I don’t think that 10 hours will be a set-in-stone rule, more like a minimum number of hours to invest in the framework I’ve chosen for the month, and in an effort to retain what I learn, I plan to write a series of articles describing my experience with the framework. I find it infinitely more valuable for personal retention to learn something for a short period of time and then explain it, either to someone in person, or to myself in writing. Hopefully you can benefit from the descriptions of my explorations. From here on out you are going to be presented with copious code examples, along with my likely more than occasional snarky commentary, but I promise the snark will only pop up when warranted.
Vue.js labels itself as The Progressive JavaScript Framework. Initially that just sounded like nice language to use when making a recommendation to a manager or product owner. “Hey, we should definitely use Vue.js in our next project. It’s progressive!” “Progressive?!? That’s fantastic! Let the rewrite begin!!!” However, in describing Vue.js as progressive, the framework authors intended to describe how Vue.js is easily adopted into a project incrementally. It has a small footprint and so it lends itself to building out small portions of your project as Vue.js apps, relieving you of the responsibility of performing wholesale rewrites and allowing you to just build the feature that is needed. At least, that is the sense I get when reading the introduction of the product by the authors. Let’s get our hands dirty with some code.
As long as you intend to have your project used on ECMAScript5 compliant browsers (good riddance, IE8!) you can use Vue.js for your next big idea. On the Vue.js website, you can download the library and include it in your .html file or point your script tag to the recommended CDN. Those are great options for experimenting and playing around with Vue.js, but it can also be installed via npm install vue
. There is also a cli tool that gives you handy commands to quickly scaffold your project. For the purpose of this article, I just pointed my little mess-around project at the CDN and moved on with the tutorial. If you decide to go with a more robust installation of Vue.js, there are ample instructions on how to Webpack, Rollup, and Browserify to your heart’s content.
At its heart, Vue.js has a template syntax that should be widely familiar to most JavaScript developers in 2017.
<div id="bodacious-app">
{ { tubular-user-message } }
</div>
Once Vue.js has bootstrapped itself to the DOM, those curly braces will get translated into whatever Vue.js hands to it. Let’s look at the JavaScript.
var app = new Vue({
el: '#bodacious-app',
data: {
tubular-user-message: 'Resplendent and most excellent salutations, brah!'
}
})
new Vue({})
can take more arguments than are seen here, but the concept is straightforward; el is the element that you wish to bind your Vue app to and data is the data you wish to pass into your template. The final product looks like this:
<!DOCTYPE html>
<html>
<head>
<script src='https://cdn.jsdelivr.net/npm/vue'></script>
</head>
<body>
<div id="bodacious-app">
{ { tubular-user-message } }
</div>
<script>
var app = new Vue({
el: '#bodacious-app',
data: {
tubular-user-message: 'Resplendent and most excellent salutations, brah!'
}
})
</script>
</body>
</html>
If you are on a mac, you can fire up a simple server in the same directory as this .html file with python -m SimpleHTTPServer 8000
, navigate your browser of choice to localhost:8000
, and see that your page does indeed render Hello Vue!
Declarative rendering. Excellent!
Not only can we pass our data into variables between curly braces, we can also bind onto element attributes. For example:
<div id="philosophical-app">
<span v-bind:id="thought-bubble">
Hover to pontificate on greater things
</span>
</div>
var app2 = new Vue({
el: '#philosophical-app',
data: {
thought-bubble: 'I think, therefore I am'
}
})
After the page is loaded, when you hover your mouse cursor over the text in the DOM, you will be presented with a hover-over bubble containing the text of thought-bubble
defined in the Vue app.
Element attribute binding. Most interesting!
Lets check out some ifs and loops.
<div id="dirty-harry">
<span v-if="lucky">
Do you feel lucky? Well, do ya, punk?
</span>
<ol>
<li v-for="action in actions">
{ { action.text } }
</li>
</ol>
</div>
var app3 = new Vue({
el: '#dirty-harry',
data: {
lucky: true,
actions: [
{ text: 'Shoot gun' },
{ text: 'Drive fast' },
{ text: 'Sleep it off' }
]
}
})
Pretty self explanatory. The value of lucky
provided by app3
is true
, which will result in the span containing the v-if
directive to display. If seen
’s value was false
, the span would not be visible in the rendered page. As for the loop, the implementation is both familiar and simple. The v-for
directive will loop through each of the actions provided by app3
and set up a temporary variable, action
, for use in the template.
Logic and Control Flow. Make my day.
Your users are going to interact with your app, and you are going to want to have your tidy little Vue app respond to their interactions. v-on
is your ticket for attaching event listeners to various elements on the page.
<div id="moria">
<p>{ { command } }</p>
<button v-on:click="emphasizeCommand">Command the beast!</button>
</div>
var app4 = new Vue({
el: '#moria',
data: {
command: 'Go back to the shadow!'
},
methods: {
emphasizeCommand: function() {
this.message = "YOU SHALL NOT PASS!!!"
}
}
})
Clicking on the Command the beast! button in the DOM will result in changing the command text to read YOU SHALL NOT PASS!!!. Really not a very useful functionality, but it does demonstrate how to register an event listener and act when the event occurs. It is easy to imagine how this could be used to fire off a POST request to a remote server to save data entered into a form or change out the DOM element for an iFramed YouTube video of dumb cats.
A future post will dig further into Event Handling in Vue.js
What I’ve shown you so far is fun, if not completely trivial, although some great building blocks have been demonstrated. You could even create a non-trivial application that lived on a small part of a page in your current, in production, application with the foundational concepts that have been shared in this post, thus proving out how Progressive Vue.js is. So far I like what I’m seeing with Vue.js, even if it is only a small sliver of how it works and what it can do. In my next post I’ll dig into the details of composing a page with multiple Vue.js components, demonstrating how Vue.js manages to keep functionality split into small shareable pieces across your application. If you’d like to learn more, check out The Official Vuejs documentation
Up next! Vue.js Instantiation, Callbacks, and TemplateSyntax.