In this tutorial, we will learn how to create a plugin in nuxt3. we will use some app hooks to create a plugin. With the help of these hooks, we will create a plugin that will show a progress bar on the top of the page.
Prerequisites
We will use NProgress package to show the bar at the top of page while the page is loading. So lets install it. And make sure to import its css or add a link to its css file.
npm install --save nprogress
<link rel="stylesheet" href="https://unpkg.com/nprogress@0.2.0/nprogress.css">
Create a plugin
Now create a folder called /plugins in the root of your project. And create a file called page-progress.js in this folder. You can name the whatever you want. Nuxt provides a helper function to create a plugin called defineNuxtPlugin.
export default defineNuxtPlugin((nuxtApp) => {
...
})
Inside this function, we will use the nuxtApp object to access hooks and show/hide the progress bar. We need two hooks i.e. page:start and page:finish.
- page:start - This hook will be called when the page starts loading.
- page:finish - This hook will be called when the page finishes loading.
First we import NProgress package and then call the NProgress.start() method in page:start hook to start showing the progress bar. And in page:finish hook, we will call the NProgress.done() method to hide the progress bar.
import NProgress from "nprogress";
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hooks.hook("page:start", () => {
NProgress.start();
});
nuxtApp.hooks.hook("page:finish", () => {
NProgress.done();
});
});
By default NProgress will show spinner at the top-right of the page and to disable it we need pass showSpinner to false.
export default ...
NProgress.configure({ showSpinner: false })
nuxtApp.hooks....
We don't need to register our plugin in the plugins array in the nuxt config because nuxt will automatically register the plugin.
Top comments (1)
is it working normaly on SSR mode