javascriptvue.jsvue-resourcevue-component

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?


Solution

  • 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);