41

In my Vue.js application I want to have some global functions. For example a callApi() function which I can call every time I need access to my data.

What is the best way to include these functions so I can access it in all my components?

  • Should I create a file functions.js and include it in my main.js?
  • Should I create a Mixin and include it in my main.js?
  • Is there a better option?
Jordy
  • 4,719
  • 11
  • 47
  • 81

3 Answers3

38

I have a file with function like a func.js like below

export const func = {
   functionName: (data) => {
      return something  
    }
}

In main.js add 2 string

import {func} from './func.js'

Vue.prototype.$func = func

and you can use from all components if in script tag like below

this.$func.functionName(somedata)

or if template tag like

$func.functionName(somedata)
36

Your best bet would be a Plugin, which lets you add features to the global vue system.

[from the vuejs Docs]

MyPlugin.install = function (Vue, options) {

// 1. add global method or property
Vue.myGlobalMethod = ...

// 2. add a global asset
Vue.directive('my-directive', {})

// 3. add an instance method
Vue.prototype.$myMethod = ...

}

Then you would just add

Vue.use(MyPlugin)

in your code before calling your function.

Vue.myGlobalMethod(parameters);

or in your case

Vue.callApi(parameters);
tony19
  • 125,647
  • 18
  • 229
  • 307
Justin MacArthur
  • 4,022
  • 22
  • 27
  • Thank you. What exactly is the difference between Mixins and Plugins (for adding global functions)? – Jordy Sep 07 '16 at 15:37
  • 1
    @Jordy the difference is that a mixin must be included in your mixin hash in your vm definition for each component that requires that functionality. A plugin makes it globally available in all your components, without requiring inclusion (since it extends the main Vue instance, each component you create already includes this functionality) – Tremendus Apps Sep 07 '16 at 16:05
  • @Jordy Tremendus has it right, Mixins are limited functionality that's added to components separately which is what I'd normally use unless a large majority of my components need that function. – Justin MacArthur Sep 07 '16 at 19:29
  • How to create plugin with webpack? – Marcelo Ribeiro Aug 09 '19 at 14:17
  • Is it the same process when using Nuxt? – Nikhil Das Nomula Nov 14 '19 at 21:32
7

Mixins can be registered globally​ too. https://v2.vuejs.org/v2/guide/mixins.html#Global-Mixin

tony19
  • 125,647
  • 18
  • 229
  • 307
Victor Bastos
  • 106
  • 1
  • 4