Nuxt patterns you will love as a Vue.js developer (Part 2)
In the first part of this series, we discovered features that enhance the development experience of Nuxt and make it one of the best frameworks to work with. Now we will demonstrate some useful patterns that can be used to provide clean solutions to some everyday problems.
$fetchState.pending, we can show a message when data is waiting to be loaded. We can also check
$fetchState.error and show an error message if there is an error fetching the data.
Refreshing page data
It’s possible to only refresh the data provided by asyncData or fetch without doing a full page refresh using the
Nuxt provides a handy helper to detect if the user is offline
Keep alive works just like with Vue and keeps the enclosed component in the memory for future re-use and improving performance.
There is an elegant pattern using the activated hook that keep alive provides and the timestamp of the last
fetch call that nuxt automatically provides in
You can use both of these to add a 30 seconds cache to
Nuxt router extra add-ons
Sometimes the file-based routing is limiting and not easy to reason about when using aliases.
routers-extra-module extends Vue router with the following features
- Multiple aliases for a single page
- Multiple params regardless of the pages directory structure
Vue Lazy hydration
vue-lazy-hydration is a renderless Vue.js component that defers the hydration of pre-rendered HTML.
scrollBehavior option lets you define custom behavior for the scroll position between routes. This method is called every time a page is rendered.
This example forces the scroll position to the top for every route:
Conveniently you can do the same thing using the scroll top property in a page level.
This component is used to purposely render a component only on client-side. To import a component only on the client, register the component inside the client-side only tag.
Using a Custom Loading Component
To create your own loader component you need to give a path to your component in the
loading option. Then, your component will be called directly by Nuxt.js. Your component has to expose a start, finish and optionally a fail and increase methods.
Nuxt image is a new directive built to provide plug-and-play image optimization for Nuxt apps. It makes it easy to integrate a CDN for images and deliver the smallest possible high-quality image so that the performance of our site doesn’t suffer.
Usage is pretty straightforward
Output uses modern responsive images techniques to provide the best image possible based on user screen resolution
Nuxt is an extremely powerful framework that's proven to work for large-scale applications. Many patterns have been created around it and elegantly solving most of the problems should be straightforward for any developer.
I hope you enjoyed this and If you have any favorite patterns please send them in the comments. Thanks!