Vue.js — the second breath of multipage apps.

When I’m starting a new project I always have to decide: should it be a Single-Page Application or is it better to keep it multi-page. Both approaches have their own pros and cons.

At These Guys we prefer lean methodology, we avoid accidental complexity as much as possible especially on early stages of a project. We use Ruby on Rails for MVP development and it gives us the ability to bootstrap and deploy online services in a matter of weeks instead of months. For almost every single problem “there’s a gem for it”, so development of such apps is roughly two times faster than SPA.

In old school Rails apps client-side logic was usually handled by jQuery. Changing the UI state was synchronous and mostly happened after form submission or clicking on a link. Modern web applications are becoming more and more complex and if you keep all your logic in jQuery then your code structure will quickly turn into a nightmare — we all know this problem.

So, what can we do if we want to quickly create a prototype that will be supportable and scalable in the future?

Vue.js to the Rescue

I noticed a trending JS framework — Vue.js. It was easy to learn it after using React.js. Most of principles are the same. Vue 1.0 uses string templates and mustache interpolation, and the in 2.0 they introduced a virtual DOM. It’s not JSX, but it allows you to use already rendered DOM as a template for your components. This allows us to reuse server-rendered html and build our app on top of it, without jQuery secret sauce or solving puzzles of build processing.

Let’s check out some example:

Same on github pages.

What’s happened?

  • At first we can see the string that rendered from server.
  • Then, when Vue is initialised the string is updated with data from JS.
  • After that, data is changing by the setTimeout call and the view updates again.

Pitfalls

To provide data for Vue app without server round-trip, we insert it as inline JS. At the same time, it would be nice to keep raw data in the Data object and organise interpolation using computed props.

To prevent every page of our app from loading the whole client app, we should use webpack code splitting. It will help to bundle only components on page and not the whole project client-side code. To integrate webpack and Rails you can use webpacked gem and its helpers.

So, your View may look like:

Certainly this approach has its own downsides, but it removes the much worse ‘j-word pain’ and leads to nice JavaScript even on multipage apps.

P.S. Given use case isn’t typical Vue example, so you better check more traditional cases to familiarise yourself with this framework.

P.S.S. This is my first article and if it will be interesting for anyone I’ll write more and provide more examples.