Vue 2.0

Posted on  by admin

In case you’ve never heard of Vue.js before: Vue.js is a front-end framework that consists of a core view layer and accompanying tools & supporting libraries.

You can read a high-level introduction to what makes it different here.

Today I am thrilled to announce the first public preview of Vue.js 2.0, which brings along many exciting improvements and new features. Let’s take a peek at what’s in store! Vue has always focused on staying light and fast, but 2.0 pushes it even further.

The rendering layer is now based on a lightweight virtual-DOM implementation (based on the awesome Snabbdom) that improves initial rendering speed and memory consumption by up to 2~4x in most scenarios (check out these benchmarks). The template-to-virtual-DOM compiler and the runtime can be separated, so you can pre-compile templates and ship your app with only the runtime, which is less than 12kb min+gzip (as a reference, React 15 is 44kb min+gzip).

In conclusion

The compiler also works in the browser, which means you can still drop in one script tag and start hacking, just like before. Even with the compiler included, the build is sitting at 17kb min+gzip, still lighter than the current 1.0 build. Now, just virtual-DOM sounds boring because there are so many implementations out there — Vue 2.0 also addresses some common drawbacks of existing virtual-DOM implementations.

Combined with the non-obtrusive reactivity system, Vue 2.0 provides optimized re-rendering out of the box without you having to do anything. Each component keeps track of its reactive dependencies during its render, so the system knows precisely when to re-render, and which components to re-render. No need for shouldComponentUpdate or immutable data structures — it just works. In addition, Vue 2.0 applies some advanced optimizations during the template-to-virtual-DOM compilation phase:.

Better performance

It detects static class names and attributes so that they are never diffed after the initial render. It detects the maximum static sub trees (sub trees with no dynamic bindings) and hoists them out of the render function. So on each re-render, it directly reuses the exact same virtual nodes and skips the diffing. These advanced optimizations can usually only be achieved via Babel plugins when using JSX, but with Vue 2.0 you can get them even using the in-browser compiler.

The new rendering system also allows you to disable reactive conversions by simply freezing your data and manually force updates, essentially giving you full control over the re-rendering process.

With these techniques combined, Vue 2.0 ensures blazing fast performance in every possible scenario while requiring minimal optimization efforts from the developer.

Migrating to Vue.js 2.0

Developers tend to have strong opinions on templates vs. On the one hand, templates are closer to HTML — they map better to the semantic structure of your app and make it much easier to think visually about the design, layout and styling.

On the other hand, templates are limited to the DSL while the programmatic nature of JSX/hyperscript provides the full expressive power of a turing-complete language. Being a designer/developer hybrid, I prefer writing most of my interfaces in templates, but in certain cases I do miss the flexibility of JSX/hyperscript.

An example would be writing a component that programmatically handles its children, something not feasible with just the template-based slot mechanism.

Well, why not have both? In Vue 2.0, you can keep using the familiar template syntax, or drop down to the virtual-DOM layer whenever you feel constrained by the template DSL.

Instead of the template option, just replace it with a render function.

More over, you can create “functional components” which are instance-less, state-less functions and use them in templates just like components!

  • The best of both worlds, in the same framework. Oh, and don’t forget you still get to use the lovely single-file components.
  • With the migration to virtual-DOM, Vue 2.0 naturally supports server-side rendering with client-side hydration.
  • One pain point of current mainstream server rendering implementations, such as React’s, is that the rendering is synchronous so it can block the server’s event loop if the app is complex.

Synchronous server-side rendering may even adversely affect time-to-content on the client.

Vue 2.0 provides built-in streaming server-side rendering, so that you can render your component, get a readable stream back and directly pipe it to the HTTP response. This ensures your server is responsive, and gets the rendered content to your users faster. With the new architecture, there are even more possibilities to explore — for example, rendering to native interfaces on mobile.

Render functions

Currently, we are exploring a port of Vue 2.0 that uses weex as a native rendering backend, a project maintained by engineers at Alibaba Group, one of the biggest tech enterprises in China.

It is also technically feasible to adapt Vue 2.0’s virtual-DOM to run inside ReactNative. We are excited to see how it goes!

Vue 2.0 is still in pre-alpha, but you can check out the source code here. Despite being a full rewrite, the API is largely compatible with 1.0 with the exception of some intentional deprecations. Check out the same official examples written in 2.0 — you will see that not much has changed!

The feature deprecations are part of our continued effort to provide the simplest API possible for maximum developer productivity. You can check out a 1.0 vs. 2.0 feature comparison here. This does mean that it will take some effort to migrate an existing app if you happen to use some of these deprecated features heavily, but we will provide detailed upgrade guides in the near future.

There is still much work left to be done. We will be releasing the first alpha once we reach satisfactory test coverage, and we are aiming for beta by end of May / early June.

In addition to tests, we also need to update the supporting libraries (vue-router, Vuex, vue-loader, vueify…). Currently only Vuex works with 2.0 out of the box, but we will make sure that everything works smoothly together when 2.0 ships.

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

We are also not forgetting about 1.x!

1.1 will be released alongside 2.0 beta, with an extended support period of 6-month critical bug fixes and 9-month security updates. It will also ship with optional deprecation warnings to get you prepared for upgrading to 2.0.

We announced Vue 2.0 back in April, and today I am very excited to release the first release candidate for Vue 2.0! From this stage on we will be in API freeze and there will be no more breaking changes before official release. All the official supporting libraries, e.g. vue-router, vuex, vue-loader & vueify have all been updated to work with Vue 2.0.

This means the 2.0 stack is technically complete — the only thing we are waiting for is documentation and release-related logistics. Despite that, we have prepared a Vue 2.0 RC Starter Resources guide to help those feeling adventurous jump right into 2.0 today.

I recently answered the question “How Popular is Vue.js in the Industry?” on Quora. You can read about the full answer here, but here are some highlights:. Based on the combined metrics including Google Trends, GitHub star history & stats.js.org statistics, Vue.js has consistently been one of the fastest growing libraries in the past few months and there’s currently no sign of slowing down.

1 million+ downloads on NPM at 125k~150k per month. 1.5 million page views & 150k monthly unique visitors on vuejs.org.

36,000+ weekly active vue-devtool users. Used by great open source projects: Laravel, GitLab, PageKit & more. Strong international adoption: biggest Chinese public companies (Alibaba, Baidu, Tencent), biggest Chinese unicorns (private companies with $1B+ valuation — Xiaomi, Didi Chuxing, DJI, Ele.me), established enterprises in Japan/UK (Line, Nintendo, Sainsbury’s).

The Vue.js patreon campign now has over $8,000 monthly pledge from the community and sponsors. It is absolutely amazing to be able to work full-time on an open source project that I am genuinely passionate about, and for that I am forever grateful to all the supporters.

I think the Vue.js patreon campaign is an interesting experiment on sustainable financial models for open source projects that demand serious commitment: it’s open source not as the by-product of a commercial company trying to help with recruiting — the only goal of the project is to create something that help more people get more things done in an easier and faster way.

It’s sustained not by revenue that possibly has nothing to do with the project itself, but rather directly by those who use it in their everyday work. To be honest, I don’t think this is a model that is easy to pull off (for that I am very lucky), but I do hope it can serve as a valuable case study for those who are interested in more sustainable open source work.

It was back in April when the Vue team started working on the new 2.0 version, and after 8 betas and 8 alphas, Vue.js 2.0 is finally here.

With the new version, there have been significant modifications made to TypeScript typings, API design, and documentation. So without further wait, let’s see what the new Vue.js 2.0 version has in store for us.

Vue’s new and modified reactivity system is now able to exactly determine components that need to be re-rendered even in large and complex component trees.

This is all because the rendering layer has been completely rewritten with the help of a lightweight Virtual DOM implementation done through snabbdom.

All libraries now support 2.0

Apart from that, the template compiler can also apply smart optimizations automatically which avoids any unnecessary diffing on re-render. With the help of component-level caching and streaming, Vue.js 2.0 is able to support superfast server side rendering. Also, vuex 2.0 and vue router support server side rendering with client side state hydration and universal routing.

Support for Server side rendering

Vue 2.0 still maintains and supports most of the template syntax compatible with 1.0 version. Though these templates are compiled into Virtual DOM render functions, developers can also directly author these render functions, if they need JavaScript flexibility.

And, there is also support for JSX. All the official tools and libraries including vue-loader, vuex, vueify, and vue-router have been updated to now support Vue.js, and the libraries have received improvements as well. If you are still using the 1.0 version, it is an absolute no-brainer that you should be migrating to the 2.0 version.

After all, Vue.js 2.0 is faster, better and more reliable. But of course, the question you are thinking of right now is – How to migrate?

Initial Setup

Luckily, there is a very extensive migration guide provided by Vue to quickly help users migrated to the 2.0 version. There was a time when Vue was just a side project, but now it has become one of the strongest growth trends in JavaScript libraries, and it is widely adopted all over the world.

With the new version, Vue.js is only going to grow.

After six months of intense development, eight alphas, eight betas and eight release candidates, Vue 2.0, “The Progressive JavaScript Framework” is finally out.

Forms in Vue.js

Being the 26th most popular JavaScript project on Github and one of the fastest growing libraries on the list (an excellent result for a project initiated less than a year ago), the new release is something to get excited about. Initially met with skepticism as another JavaScript framework, Vue evolved into a fully-fledged, yet agile, JavaScript framework. At its inception, many developers considered Vue to be a lighter version of Angular.

While some fundamental similarities exist (e.g. ng-if), the team behind Vue chose to import already working features and supplement and optimize them with improved functional elements.

For example, compared to Angular 1, Vue has a distinct separation between directives and components, avoiding the typical confusion specific to Angular 1.

Another example can be the way Vue enforces the data flow between components. Unlike Angular, which uses a two-way binding between scopes, Vue adopts a one-way data flow between elements, which is a significant advantage for the developer looking for a nimble app.

In fact, Vue focuses on flexibility and simplicity where Angular adopts rigidity and strictness.

What about Angular 2? The seasoned developer will also notice that some Angular 2 features are strikingly similar to Vue.

And while Angular 2’s performance is impressive and on par with Vue, one should notice that a full-featured Vue 2.0 with compiler included weighs 23kb and is still lighter than the bare-bones version of Angular 2 (50kb).

Tracking a Form Input

Furthermore, Angular 2 is developed with focus on large enterprise applications.

  • Vue is also well-suited to enterprise environments, but it is also friendly in less demanding environments.
  • So, what’s new in Vue 2.0? The code is entirely rewritten to enhance Vue’s scalability and modularity.

The new rendering layer is based on a virtualized DOM implementation which offers significant improvements in rendering speed and memory consumption. And while usually virtual-DOM implementations suffer from performance issues like re-rendering, thanks to its reactive capabilities, Vue manages to limit the impact of this bottleneck.

The Holy Grail of javascripting, server-side rendering, is supported in Vue with streaming and component-level caching.

With Postcards you can create and edit email templates online without any coding skills! Includes more than 100 components to help you create custom emails templates faster than ever before. The new rendering layer provides significant performance improvements compared to v1, and makes Vue 2.0 one of the fastest frameworks out there.

In addition, it requires minimal effort in terms of optimization because Vue’s reactivity system is able to precisely determine components that need to be re-rendered in a large and complex component tree, according to Evan You via medium.com.

In a UI rendering scenario, where manipulating the DOM is the most resource intensive operation Vue.js will offer a 20 to 50 percent performance boost, because of the way Vue deals with overheads on DOM manipulations.

  • In fact, an unoptimized, out-of-the-box Vue is faster than a fully-optimized React implementation. A more detailed description of the Vue.js performance compared to React.js can be found here. Another optimization is the filter system which was adjusted to favor scalability. Vue ships to developers without any built-in filters, however, filters can still be used inside text inside text interpolations ({{}} tags).
  • Developers can invoke standalone libraries such as moment.js or accounting js for formatting dates and subsequently currencies. The filter syntax also receives a make-up bring it in line with JavaScript’s {{ date | formatDate(‘YY-MM-DD’) }} function invocation. Additionally, in Vue 2.0 developers get maximum flexibility in terms of development style. The template-to-virtual-DOM compiler and the runtime can be separated, allowing for shipping pre-compiled templates, and, subsequently, runtime only apps.

You said “the 2.0 runtime-only build weighs at only 16kb min+gzipped, and totals at 26kb even with vue-router and vuex included, on par with the v1 core alone!”. From a compatibility standpoint, except some minor deprecations, Vue 2.0 is broadly compatible with previous iterations.

Check out the same official examples written in 2.0 – you will see that not much has changed! If you enjoy freedom instead of the “right way,” the source code for Vue 2.0 is available on GitHub. The documentation, including the deprecated features, is here. It is easy to learn. Download the webpack template, and you are ready to go. All you need is basic HTML and JavaScript skills. In fact, a weekend should be enough to get acquainted with Vue and build your first app, especially if you follow this guide.

Have you already developed a nice app? Share it with us at #designmodo. With Startup App and Slides App you can build unlimited websites using the online website editor which includes ready-made designed and coded elements, templates and themes.

Thanks to a collaboration with Weex, a cross-platform UI framework developed by Alibaba Group, which adopted Vue as its JavaScript framework runtime, Vue is about to become platform agnostic.

The components authored with Vue will be rendered natively on iOS and Android.

Displaying Results From GitHub

While still a work in progress, the project is actively developed and will be ready in the coming months.

When the component is created, we want to listen for any new-username events that are emitted on the message bus. Thankfully, Vue supports a number of lifecycle hooks, including created. Because we’re responsible developers, let’s also stop listening for events when the component is destroyed by using the destroyed event:

We then define the onUsernameChange method, which will be called and will set the currentUsername property:

Note that we don’t have to explicitly bind the onUsernameChange method to the current scope. When you define methods on a Vue component, Vue automatically calls myMethod.bind(this) on them, so they’re always bound to the component. This is one of the reasons why you need to define your component’s methods on the methods object, so Vue is fully aware of them and can set them up accordingly.

Conditional Rendering

If we don’t have a username — as we won’t when the component is first created — we want to show a message to the user. Vue has a number of conditional rendering techniques, but the easiest is the v-if directive, which takes a condition and will only render the element if it exists. It also can be paired with v-else:

Once again, this will look very familiar to any Angular developers. We use double equals rather than triple equals here because we want the conditional to be true not only if currentUsername is null but also if it’s undefined, and nullundefined is true.

Fetching from GitHub

Vue.js doesn’t ship with a built-in HTTP library, and for good reason. These days the fetch API ships natively in many browsers (although at the time of writing, not IE11, Safari or iOS Safari). For the sake of this tutorial I’m not going to use a polyfill, but you can easily polyfill the API in browsers if you need to. If you don’t like the fetch API there are many third-party libraries for HTTP, and the one mentioned in the Vue docs is Axios.

I’m a big proponent of frameworks like Vue not shipping with HTTP libraries. It keeps the bundle size of the framework down and leaves it to developers to pick the library that works best for them, and easily customize requests as needed to talk to their API. I’ll stick to the fetch API in this article, but feel free to swap it out for one that you prefer.

If you need an introduction to the fetch API, check out Ludovico Fischer’s post on SitePoint, which will get you up to speed.

To make the HTTP request, we’ll give the component another method, fetchGithubData, that makes a request to the GitHub API and stores the result. It will also first check to see if we already have data for this user, and not make the request if so:

We then finally just need to trigger this method when the username changes:

There’s one other thing to be aware of, due to the way that Vue keeps track of the data you’re working with so that it knows when to update the view. There is a great Reactivity guide which explains it in detail, but essentially Vue isn’t able to magically know when you’ve added or deleted a property from an object, so if we do:

Vue won’t recognize that and won’t update our view. Instead, we can use the special Vue.set method, which explicitly tells Vue that we’ve added a key. The above code would then look like so:

This code will modify this.githubData, adding the key and value that we pass it. It also notifies Vue of the change so it can rerender.

Now our code looks like so:

Finally, we need to register the GitHubOutput component with the App component:

And include it in the template:

Although we haven’t yet written the view code to show the fetched data on screen, you should be able to fill in the form with your username and then inspect the Vue devtools to see the data requested from GitHub. This shows how useful and powerful these devtools are; you can inspect the local state of any component and see exactly what’s going on.

Showing Some Stats in the View

We can now update the template to show some data. Let’s wrap this code in another v-if directive so that we only render the data if the request has finished:

With that, we can now render the GitHub details to the screen, and our app is complete!

Refactors

There are definitely some improvements we can make. The above bit of HTML that renders the GitHub data only needs a small part of it — the data for the current user. This is the perfect case for another component that we can give a user’s data to and it can render it.

Let’s create a GithubUserData component, following the same structure as with our other components:

There’s only one tiny difference with this component: it’s going to take a property, data, which will be the data for the user. Properties (or, “props”) are bits of data that a component will be passed by its parent, and they behave in Vue much like they do in React. In Vue, you have to explicitly declare each property that a component needs, so here I’ll say that our component will take one prop, data:

One thing I really like about Vue is how explicit you have to be; all properties, data, and components that a component will use are explicitly declared. This makes the code much nicer to work with and, I imagine, much easier as projects get bigger and more complex.

In the new template, we have exactly the same HTML as before, although we can refer to data rather than githubData[currentUsername]:

To use this component we need to update the GithubOutput component. Firstly, we import and register GithubUserData:

You can use any name for the component when declaring it, so where I’ve placed github-user-data, you could place anything you want. It’s advisable that you stick to components with a dash in them. Vue doesn’t enforce this, but the W3C specification on custom elements states that they must contain a dash to prevent naming collisions with elements added in future versions of HTML.

Once we’ve declared the component, we can use it in our template:

The crucial part here is how I pass the data property down to the component:

The colon at the start of that attribute is crucial; it tells Vue that the attribute we’re passing down is dynamic and that the component should be updated every time the data changes. Vue will evaluate the value of githubData[currentUsername] and ensure that the GithubUserData component is kept up to date as the data changes.

If you find :data a bit short and magical, you can also use the longer v-bind syntax:

The two are equivalent, so use whichever you prefer.

Conclusion

With that, our GitHub application is in a pretty good state! You can find all the code on GitHub and even check out the application running online.

I had high hopes when getting started with Vue, as I’d heard only good things, and I’m happy to say it really met my expectations. Working with Vue feels like taking the best parts of React and merging them with the best parts of Angular. Some of the directives (like v-if, v-else, v-model and so on) are really easy to get started with (and easier to immediately understand than doing conditionals in React’s JSX syntax), but Vue’s component system feels very similar to React’s.

You’re encouraged to break your system down into small components, and all in all I found it a very seamless experience. I also can’t commend the Vue team highly enough for their documentation: it’s absolutely brilliant. The guides are excellent, and the API reference is thorough yet easy to navigate to find exactly what you’re after.

If you’ve enjoyed this post and would like to learn more, the best place to start is definitely the official Vue.js site.

Share This Article

Jack Franklin

I'm a JavaScript and Ruby Developer working in London, focusing on tooling, ES2015 and ReactJS.

Up Next