Chris does a lot of work on the official Vue.js documentation and tooling. In this talk he goes over a series of productivity boosts, radical tweaks, and unlocked possibilities to help you write better Vue applications.
It’s a common pattern to have a method that needs to get called on component creation and then again when a watched property changes:
However, this can be optimized by like so, by specifying “immediate: true” which will run the moment it’s registered.
When you have frequently used components you may have to import many files all over the place.
You can use component registration to include many different files. He includes this in “src/main.js” or “/components/_globals.js”:
He doesn’t recommend doing this with all components, because you may end up having components that you don’t need in the long run.
Just like component registration, module registration can start to get tedious.
To solve this he creates a /modules/index.js which has the following content:
Also while in this file sometimes he will namespace his modules. Changing to the following code:
Now the code from above, where we had to import all the modules can change to:
Lazy Loaded Routes
Sometimes you may have parts of your website that are only accessible to a part of your users. See this code:
With this code everyone is forced to download the admin files just in case they need it. Fortunately there’s a small change we have to make to lazy load this route:
You won’t want to do this with all your components, as there would be additional load time for the user.
In a base input component we may want to have a template that works with v-model, so we might have the following code.
But if I want to listen for a focus event, and add a label element it could break:
To solve this I need to define a computed property which returns an object of all the listeners from the parent.
This then works as we want. However, what happens when we add a placeholder attribute that we want to pass through to
We can use
inheritAttrs to get fully transparent wrappers like so:
As you can see, the
placeholder attribute is now getting applied to the
<input> element as we want.
Single Root Components
As a Vue developer you’re probably familiar with the following error, about only having a single root element:
Normally the solution is to wrap it in a div. However, sometimes there are patterns where this limitation doesn’t work well. For example: routes that create multiple list items like so:
The solution here is to use a functional component, which can return an array of elements.
Sometimes you have multiple transitions, and it can get a little annoying to have multiple v-if statements.
One way to solve this is to create a TheaterCurtains component which uses another functional component.
If you want to see more of Chris’s best practices he created a Vue Enterprise Boilerplate which contains many of these and more.