position |
---|
9 |
We use Nuxt Plugins when adding app-level functionality. Plugins provide
better configurability and helps keeping app.vue
setup cleaner. To create a
plugin, create a directory named plugins
and files which are located in this
directory will be autmatically registered. We prefer using object syntax to
create a plugin. Demo is at /demo/plugins.
export default defineNuxtPlugin({
name: "demo",
setup () {
...
},
hooks:{
...
}
})
Note
Files which are not located in the root /plugins
directory are not
automatically registered, they should be added in nuxt.config
manually
We can register to Nuxt
runtime hooks to provide functionality such as
handling exceptions.
hooks: {
'app:error'(error) {
...
}
}
Helpers can be provided on nuxtApp
and can be accessed by nuxtApp.${helper}
name. Use the sample below to provide helpers on nuxtApp
instance.
// plugin
setup() {
const counter = useCounter(); // custom composable
return {
provide: {
counter
}
}
}
// index.vue
<script setup>
const counter = useNuxtApp().$counter
</script>