Published on

Global method in Nuxt.js using injection (extend Nuxt functionalities)

Author
  • Name
    A. Fauzi
    Title
    Human Being

In this post, I'm gonna give an example of how to define a global method across Nuxt applications and call it in any components using $root & context injection method.

First, create a new custom plugin in the plugins directory, and name it anything you want, I'm gonna name it global.js.

Once you created the plugin file, wrap your method/function inside this block of code

export default (context, inject) => { // write your variables or methods here const sayHelloFn = (name) => { console.log(`Hello ${name}`) } inject('sayHello', sayHelloFn) }

Then add the newly created plugin to the project configuration nuxt.config.js

... plugins: [ '~/plugins/global.js', ], ...

And now you can use your method anywhere, for example

// On the server-side: ... import { useContext } from '@nuxtjs/composition-api' setup() { const { $sayHello } = useContext() onMounted(() => { $sayHello('Fauzi') }) } // On the client-side <template> <div>this.$sayHello('Fauzi')</div> </template>

You can read other ways to extend the functionalities of Nuxt app here: https://nuxtjs.org/docs/directory-structure/plugins/#combined-inject