7 Vue.js features you should use more often

Let's be realistic: reading documentation is not something most of us want to do and spend our time on. However, it would really fall to do so when we intend to work with modern frontend frameworks (like Vue) that are constantly evolving and changing with each release.

Here we will look at features that are interesting but not very popular. Note that everything below is part of the official Vue documentation.

1. Loading status support

For larger applications, you can split the application into smaller parts and load a component from the server if you need to. To make this easier for us, Vue allows you to define your component as a factory that asynchronously loads the component. Vue will run the factory function when the component needs to be rendered and will store the results in memory for future re-renders. As of version 2.3, the factory can also return an object in the following format:

const AsyncComponent = () => ({ // The component to load (should be a Promise) component: import('./MyComponent.vue'), // A component to use while the async component is loading loading: LoadingComponent, // A component to use if the load fails error: ErrorComponent, // Delay before showing the loading component. Default: 200ms. delay: 200, // The error component will be displayed if a timeout is // provided and exceeded. Default: Infinity. timeout: 3000 })

With this approach you have additional options for loading, error states, delays in extracting components and when timeouts expire.

2. Cheap Static Components z “v-once”

Rendering pure HTML components is very fast in Vue. Sometimes you may have components that contain a lot of static content. In these cases, you make sure that this is only run once and then falls into cache, by adding a v-once directive to the root element:

Vue.component('terms-of-service', { template: ` <div v-once> <h1>Terms of Service</h1> ... a lot of static content ... </div> ` })

3. Recursive components

Components can recursively call themselves in their own template. However, they can only do this if they have the name option set. If you are not careful, recursive components can lead to an infinite loop:

name: 'stack-overflow', template: '<div><stack-overflow></stack-overflow></div>'

A component like the one above will cause an error that reads "max stack size exceeded". So make sure the recursive call is conditional (e.g. uses v-if, which will eventually be false).

4. Inline templates

When the special inline-template attribute is present in a child component, that component will use the internal content as its template, rather than treating it as content. This allows for more flexible template creation.

<my-component inline-template> <div> <p>These are compiled as the component's own template.</p> <p>Not parent's transclusion content.</p> </div> </my-component>

According to what /u/JZumun pointed out on Reddit, Inline templates are one of the 3 deprecated features of Vue - that's why they should rather not be used. Tag script and default slot are alternatives.

5. Dynamic directive arguments

Directive arguments can be dynamic. For example, in v-mydirective:[argument]="value", the argument can be updated based on data from the component instance. This makes custom directives flexible and can be used anywhere in the application.

Here is a directive where a dynamic argument can be updated in any component instance.

<div id="dynamicexample"> <h3>Scroll down inside this section ↓</h3> <p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p> </div> Vue.directive('pin', { bind: function (el, binding, vnode) { el.style.position = 'fixed' var s = (binding.arg == 'left' ? 'left' : 'top') el.style[s] = binding.value + 'px' } }) new Vue({ el: '#dynamicexample', data: function () { return { direction: 'left' } } })

6. Event and key modifiers

For the .passive, .capture and .once event modifiers, Vue gives us prefixes to use with on:

For example:

on: { '!click': this.doThisInCapturingMode, '~keyup': this.doThisOnce, '~!mouseover': this.doThisOnceInCapturingMode }

For all other event and key modifiers, the prefix is not required because you can use event methods in the handler:

7. Dependency injection (Provide/Inject)

There are several ways for two components to communicate with each other in Vue - each has advantages and disadvantages, of course. A new feature introduced in version 2.2 is the use of dependency injection with Provide/Inject.

This pair of options is used together to allow a parent component to inject dependencies into all of its subcomponents, no matter how deep the component hierarchy is and as long as they are in the same parent chain.

If you're familiar with React, the above is very similar to the context function there.

// parent component providing 'foo' var Provider = { provide: { foo: 'bar' }, // ... } // child component injecting 'foo' var Child = { inject: ['foo'], created () { console.log(this.foo) // => "bar" } // ... }

Summary

Staying up to date is hard and takes time. The best solution is to keep an eye on the Vue Twitter account, follow the official release announcements and read the publication of articles about Vue on Medium.

In addition, Vue 3 also has a lot of new features that are worth getting familiar with before migrating. Let us know what you think in the comments.

The original article in Polish can be found here.

14 May 2021