How to include global functions in Vue.js?

Sometimes, we want to include global functions in Vue.js.

In this article, we’ll look at how to include global functions in Vue.js.

How to include global functions in Vue.js?

To include global functions in Vue.js, we can create our own plugin.

For instance, we write

MyPlugin.install = (Vue, options) => {
  Vue.myGlobalMethod = () => {
    //...
  };

  Vue.directive("my-directive", {});

  Vue.prototype.$myMethod = function () {
    //...
  };
};

to create the MyPlugin plugin.

We set its install method to a function that adds a global static method with

Vue.myGlobalMethod = () => {
  //...
};

We add a directive with

Vue.directive("my-directive", {});

And we add an instance method with

Vue.prototype.$myMethod = function () {
  //...
};

Then we register the plugin with Vue.use by writing

Vue.use(MyPlugin)

We can call global static methods with

Vue.myGlobalMethod(parameters);

And we call component instance methods with

this.$myMethod 

in a component.

Conclusion

To include global functions in Vue.js, we can create our own plugin.