digital

Vue.js Recipes

This is a record of some gotchas I’ve come across with Vue.js v2. I love its simplicity.

Caveat: examples are taken from real code, but I have not tested them directly. If you see a problem, please contact me.

Contents of this post:

  • AJAX Request
  • kebab-case for Props with HTML Components
  • Force Refresh of Object

AJAX Request

Include Axios:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Make the request, noting the self trick to keep a reference to this:

Vue.component('my-vue-component', {
  ...
  data: {
    widgets: null
  },
  methods: {

fetchData: function() {
      let self = this;
      axios.get("/api/widgets")
        .then(function (response) {
          self.widgets = response.data;
        })
        .catch(function (error) {
          console.log(error);
        });
    }
  }
  ...
});

kebab-case for Props with HTML Components

Use camelCase in the JavaScript, and kebab-case in the HTML.

This is the HTML template for your component, note how the widgetName changes to widget-name:

<template id="widget-editor">
  <p>{{ widgetName }}</p>
</template>

<div id="my-app">
  <widget-editor :widget-name="Weather Widget"></widget-editor>
</div>

Javascript for the component:

Vue.component('widget-editor', {
  // camelCase in JavaScript
  props: ['widgetName'],
  template: '#widget-editor'
})

Force refresh of object

Problem: let’s say you have a component that displays a model, like a “todo list” which contains another component “todo item”. If you load new data for that todo list itme from the server, you might want the todo list item component to be recreated completely so that it goes through all its initialisation steps. If you don’t destroy the model, you component might have state from the older model. For example, you might forget to reset a boolean flag “show top priority item” when the item changes. Most of this is covered by how Vue.js watches for changes in its properties you set. This is more about overcoming programmer bugs. Maybe this really isn’t a problem, and I didn’t understand what the correct approach should have been.

Controversial approach: Vue.js documentation advises you to be “data-centric”. In other words, instead of destroying and re-creating an object, you should watch for changes in your component of that object. But I’ve found in one case it was cleaner to destroy (nullify) the object first, then assign a new object to the variable, so that no state is left over from the older object.

HTML:

<template id="todo-list">
  <p>
    My one thing to do:
    <todo-item :item-object="topPriorityItem" v-if="topPriorityItem"></todo-item>
</template>

JavaScript:

Vue.component('todo-list', {
  data: {
    todoItems: ['Get kebab', 'Go for a walk'],
    topPriorityItem: null
  },
  methods: {
    setTopPriority: function(itemIndex) {
      this.topPriorityItem = null;
      this.$nextTick(function() {
        // Trick: waits until next "tick" to ensure that item nullification destroys <todo-item>
        this.topPriorityItem = this.todoItems[itemIndex];
      });
    }
  }
}
Vue.component('todo-item', {
  props: [itemObject],
  mounted: function() {
    // Complicated state setting here that would be hard to track
    // if the item wasn't destroyed and recreated
  }
});

Vue.js and Choosing Simplicity

I’m a fan of Vue.js, a progressive JavaScript framework.

Vue.js can be used in two ways:

  1. Direct <script> include
  2. NPM

Even with Vue, you have the choice to choose simplicity (direct include) or to choose advanced features (NPM building).

In fairness to the Vue.js documentation, they warn you against the NPM route unless you’re building a “large scale application”.

Use the “Direct Include” Method for Vue’s Progressiveness

What does Vue do really well? It lets you include their CDN-hosted .js file, and in 5 minutes you have a dynamic web page. That’s the implementation of its progressiveness.

When you’re testing out Vue, just include its script direclty. Don’t start building in NPM.

“But I’m too cool, I need NPM.”

If you know you need NPM, this article is already not for you. It is, however, a suggestion to use the direct include method for as long as you can.

The biggest reason I have to not use NPM (and this is subjective): it will present a whole extra technological barrier to letting other developers work on your application. It’s very easy for us techies to forget how many layers of technology you need to understand to get a complex application built, deployed, and maintained. It’s only when you try to explain the application to a second developer that you might suddenly realise all the brain complexity involved just for delving into developing the application.

It can be an ego thing, admit it. If you choose a solution that’s “too simple”, you might be afraid of people judging you as “too simple”.

In Summary

In an iPhone-wielding, Macbook-wielding, hipster-inspired, checked shirts-dominated world, it’s easy to want to use the more cool (and complicated) approach.

But stepping back and choosing the simplest technological solution can often win out over advanced complexity.

An Ode to Vue.js

The web’s flexible simplicity

I’ve loved the web for many years for its basic but flexible simplicity.

I’m in awe of Roy Fielding, Tim Berners-Lee and however influential people who formed what the web (and internet) became. Their solutions are in a way incredibly complex, but in another dimension could be judged as overly-simplistic. But their solutions won out as a technical platform that’s difficult to fully appreciate.

In the world of developing for the web, there was a time when server-side rendering was just easier than in-browser rendering of data in a web application. Things got complicated; Angular v1 happened.

But out of a mess, simplicity wins out. And that is Vue.

Vue for developing the web

I’m quite excited about Vue.js, which is indeed a progressive JavaScript framework.

I’ve been using it to create a quiz-management interface for Bitesize Irish Gaelic. After that I’ll be developing the front-end of the feature in Vue. I hope to write a case study on it, once the feature is live.

To give you context, I like trimmed-down frameworks for web application development. For example, I’ve been a fan of the Slim PHP framework over the past few years, which does just enough really well. Keep it simple, stupid.

With Vue, it’s almost “too easy” to be able to add interactivity to a page. In the end, it’s the progressiveness that makes it shine for me. You can include the framework from a public URL in your HTML page, and quickly add interactivity. Once I figured out the structure that Vue expects, I was able to intuitivlely add interactivity to a page, like binding a piece of data to a form element. I knew exactly how to make an element like a button call a method that could interact with data in the page.

Include the Axios HTTP client in the same page, and you can dynamically show data from an API.

There are some catches, as always. You have to figure out Vue’s declarative nature. I had come across this with Angular v1, but it still took a little time to get used to. At the time of writing you can’t use camelCasing for naming events or “props” for components.

You’ll soon want single-file components in Vue.js, which will bring you to building your application instead of just including the framework in the HTML page. When you’ve gotten this far, you’re already launched into the possibilities of Vue.

See also: Vue.js and Choosing Simplicity