Tuesday, November 29, 2016

Getting up and Running with the Vue.js 2.0 Framework

Back in September, the popular JavaScript framework Vue.js released v2 and ever since I've been really eager to give it a spin and see what it's like to work with. As someone who's pretty familiar with Angular and React, I was looking forward to seeing the similarities and differences between them and Vue.

Vue 2 sports excellent performance stats, a relatively small payload (the bundled runtime version of Vue weighs in at 16kb once minified and gzipped), along with updates to companion libraries like vue-router and vuex, the state management library for Vue. There's far too much to cover in just one article, but keep an eye out for a later article where we'll look more closely at some of the libraries that couple nicely with the core framework.

Inspiration from Other Libraries

As we go through this tutorial you'll see many features that Vue has that are clearly inspired by other frameworks. This is a good thing; it's great to see new frameworks take some ideas from other libraries and improve on them. In particular, you'll see Vue's templating is very close to Angular, but its components and component lifecycle methods are closer to React (and Angular 2, as well).

One such example of this is that, much like React and nearly every framework in JavaScript land today, Vue uses the idea of a virtual DOM to keep rendering efficient. Vue uses a fork of snabbdom, one of the more popular virtual DOM libraries. The Vue site includes documentation on its Virtual DOM rendering, but as a user all you need to know is that Vue is very good at keeping your rendering fast (in fact, it performs better than React in many cases), meaning you can rest assured you're building on a solid platform.

Components, Components, Components

Much like other frameworks these days, Vue's core building block is the component. Your application should be a series of components that build on top of each other to produce the final application. Vue.js goes one step further by suggesting (although not enforcing) that you define your components in a single .vue file, which can then be parsed by build tools (we'll come onto those shortly). Given that the aim of this article is to fully explore Vue and what it feels like to work with, I'm going to use this convention for my application.

A Vue file looks like so:

<template>
  <p>This is my HTML for my component</p>
</template>

<script>
export default {
  // all code for my component goes here
}
</script>

<style scoped>
  /* CSS here
   * by including `scoped`, we ensure that all CSS
   * is scoped to this component!
   */
</style>

Alternatively, you can give each element a src attribute and point to a separate HTML, JS or CSS file respectively if you don't like having all parts of the component in one file.

Setting up a Project

Whilst the excellent [Vue CLI][http://ift.tt/1JBk14p] exists to make setting up a full project easy, when starting out with a new library I like to do it all from scratch so I get more of an understanding of the tools.

These days Webpack is my preferred build tool of choice, and we can couple that with the vue-loader plugin to support the Vue.js component format that I mentioned previously. The final thing we'll need is Babel and the ES2015 preset, so we can write all our code in lovely ES2015 syntax.

Setting up the Webpack configuration boils down to the following:

  • Make Webpack build from src/main.js, and output into build/main.js
  • Tell Webpack to use the vue-loader for any .vue files
  • Tell Webpack to use Babel for any .js files
  • Tell the vue-loader that it should use Babel to transpile all JavaScript. This means that when we include JavaScript in our *.vue files, it will be transpiled through Babel.
module.exports = {
  entry: './src/main',
  output: {
    path: './build',
    filename: 'main.js',
  },
  module: {
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue',
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
      },
    ],
  },
  vue: {
    loaders: {
      js: 'babel',
    },
  },
}

Finally, we'll create an HTML file and we're ready to go!

<!DOCTYPE html>
<html>
  <head>
    <title>My Vue App</title>
  </head>
  <body>
    <div id="app">
    </div>
    <script src="/build/main.js"></script>
  </body>
</html>

We create an empty div with the ID of app as this is the element that we're going to place our Vue application in. I always prefer to use a div, rather than just the body element, as that lets me have control over the rest of the page.

Writing Our First Vue.js App

We're going to stay true to every programming tutorial ever and write a Vue application that puts "Hello World" onto the screen before we dive into something a bit more complicated.

Each Vue app is created by importing the library and then instantiating a new Vue instance:

import Vue from 'vue'

const vm = new Vue({
  el: '#app',
})

We give Vue an element to render onto the page, and with that, we've created a Vue application! We pass a selector for the element that we want Vue to replace with our application. This means when Vue runs it will take the div#app that we created and replace it with our application.

The reason we use the variable name vm is because it stands for "View Model". Although not strictly associated with the "Model View View-Model" (MVVM) pattern, Vue was inspired in part by it, and the convention of using the variable name vm for Vue applications has stuck. Of course, you can call the variable whatever you'd like!

So far, our application isn't doing anything, though, so let's create our first component, App.vue, that will actually render something onto the page.

Vue doesn't dictate how your application is structured, so this one is up to you; I ended up creating one folder per component, in this case App (I like the capital letter, signifying a component), with four files in it:

  • index.vue
  • template.html
  • script.js
  • style.css

App/index.vue simply imports the other three files:

<template src="./template.html"></template>
<script src="./script.js"></script>
<style scoped src="./style.css"></style>

I like calling it index.vue, but you might want to call it app.vue too so it's easier to search for. I prefer importing App/index.vue in my code versus App/app.vue, but again you might disagree, so feel free to pick whatever you and your team like best.

For now, our template is just <p>Hello World</p>, and I'll leave the CSS file blank. The main work goes into script.js, which looks like so:

export default {
  name: 'App',
  data() {
    return {}
  },
}

Doing this creates a component which we'll give the name App, primarily for debugging purposes, which I'll come onto later, and then define the data that this component has and is responsible for. For now, we don't have any data, so we can just tell Vue that by returning an empty object. Later on, we'll see an example of a component using data.

Now we can head back into src/main.js and tell the Vue instance to render our App component:

Continue reading %Getting up and Running with the Vue.js 2.0 Framework%


by Jack Franklin via SitePoint

No comments:

Post a Comment