Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include global functions in Vue.js

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?
like image 408
Jordy Avatar asked Sep 07 '16 14:09

Jordy


People also ask

How do you make a global function in Vue?

Using Mixins A Mixin is an object that contains the same options as a component and can be reused and distributed between Vue components. We will create a globalHelper function inside a Mixin and call it from a component.

Does Vue have functional components?

Functional components are a great tool to have in your Vue. js toolbelt. They are especially handy if you render hundreds or thousands of component instances in one page, where each component is responsible for displaying data.


1 Answers

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); 
like image 85
Justin MacArthur Avatar answered Sep 28 '22 20:09

Justin MacArthur