title: Vue/Nuxt: How to define a global method accessible to all components?
body: <p>I just want to be able to call</p>
  
  <pre><code>{{ globalThing(0) }}
  </code></pre>
  
  <p>in templates, without needing to define globalThing in each .vue file.</p>
  
  <p>I've tried all manner of plugin configurations (or mixins? not sure if Nuxt uses that terminology.), all to no avail.  It seems no matter what I do, <code>globalThing</code> and <code>this.globalThing</code> remain undefined.</p>
  
  <p>In some cases, I can even debug in Chrome and see this <code>this.globalThing</code> is indeed defined... but the code crashes anyway, which I find very hard to explain.</p>
  
  <p>Here is one of my many attempts, this time using a plugin:</p>
  
  <p>nuxt.config.js:</p>
  
  <pre><code>plugins: [
      {
          src: '~/plugins/global.js',
          mode: 'client'
      },
  ],
  </code></pre>
  
  <p>global.js:</p>
  
  <pre><code>import Vue from 'vue';
  Vue.prototype.globalFunction = arg =&gt; {
      console.log('arg', arg);
      return arg;
  };
  </code></pre>
  
  <p>and in the template in the .vue file:</p>
  
  <pre><code>        &lt;div&gt;gloabal test {{globalFunction('toto')}}&lt;/div&gt;
  </code></pre>
  
  <p>and... the result:</p>
  
  <p>TypeError
  _vm.globalFunction is not a function</p>
  
  <hr>
  
  <p>Here's a different idea, using Vuex store.</p>
  
  <p>store/index.js:</p>
  
  <pre><code>export const actions = {
      globalThing(p) {
          return p + ' test';
      }
  };
  </code></pre>
  
  <p>.vue file template:
          test result: {{test('fafa')}}</p>
  
  <p>.vue file script:</p>
  
  <pre><code>import { mapActions } from 'vuex';
  
  export default {
  
      methods: {
          ...mapActions({
              test: 'globalThing'
          }),
      }
  };
  </code></pre>
  
  <p>aaaaaaaaand the result is.........</p>
  
  <p>test result: [object Promise]</p>
  
  <p>OK, so at least the method exists this time. I would much prefer not to be forced to do this "import mapActions" dance etc. in each component... but if that's really the only way, whatever.</p>
  
  <p>However, all I get is a Promise, since this call is async. When it completes, the promise does indeed contain the returned value, but that is of no use here, since I need it to be returned from the method.</p>
  
  <hr>
  
  <p>EDIT</p>
  
  <p>On the client, "this" is undefined, except that..... it isn't! That is to say, </p>
  
  <pre><code>console.log('this', this); 
  </code></pre>
  
  <p>says "undefined", but Chrome's debugger claims that, right after this console log, "this" is exactly what it is supposed to be (the component instance), and so is this.$store! </p>
  
  <p>I'm adding a screenshot here as proof, since I don't even believe my own eyes.</p>
  
  <p><a href="https://i.stack.imgur.com/50ueW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/50ueW.png" alt="just plain not possible"></a></p>