Vue/Nuxt: How to define a global method accessible to all components?

  1. Use Nuxt's inject to get the method available everywhere
export default ({ app }, inject) => {
  inject('myInjectedFunction', (string) => console.log('That was easy!', string))
}
  1. Make sure you access that function as $myInjectedFunction (note $)
  2. Make sure you added it in nuxt.config.js plugins section

If all else fails, wrap the function in an object and inject object so you'd have something like $myWrapper.myFunction() in your templates - we use objects injected from plugins all over the place and it works (e.g. in v-if in template, so pretty sure it would work from {{ }} too).

for example, our analytics.js plugin looks more less:

import Vue from 'vue';
const analytics = {
    setAnalyticsUsersData(store) {...}
    ...
}

//this is to help Webstorm with autocomplete
Vue.prototype.$analytics = analytics;

export default ({app}, inject) => {
    inject('analytics', analytics);
}

Which is then called as $analytics.setAnalyticsUsersData(...)

P.S. Just noticed something. You have your plugin in client mode. If you're running in universal, you have to make sure that this plugin (and the function) is not used anywhere during SSR. If it's in template, it's likely it actually is used during SSR and thus is undefined. Change your plugin to run in both modes as well.


https://nuxtjs.org/guide/plugins/

Nuxt explain this in Inject in $root & context section.

you must inject your global methods to Vue instance and context.

for example we have a hello.js file.

in plugins/hello.js:

export default (context, inject) => {
  const hello = (msg) => console.log(`Hello ${msg}!`)
  // Inject $hello(msg) in Vue, context and store.
  inject('hello', hello)
  // For Nuxt <= 2.12, also add 👇
  context.$hello = hello
}

and then add this file in nuxt.config.js:

export default {
  plugins: ['~/plugins/hello.js']
}