← Home

How to make global functions in Vue.js

June 16, 2020

A function or a method defined inside a component in Vue.js would not be accessible to all other components, it may happen that another component requires this function. Placing a function outside of a component will not help you when working with Vue.js.

Let’s find out how to create a global function that can be called from anywhere without making any imports.

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.

Open your main file then create a global mix:

  methods: {
    globalHelper: function () {
      alert("Hello world")

Now all of the above Mixin options will be automatically implemented for all components. For example, we can call the function from the component template:

<div v-on:click="globalHelper">Click me</div>

Using Plugins

Plugins can also add global functions to Vue. So let’s create a simple plugin containing our global function. In our main file, we can add the plugin directly or create and import it from a separate file.

const MyPlugin = {
  install(Vue, options) {
    Vue.prototype.globalHelper = () => {
      alert("Hello world")

Now we can make the same call as we did before

<div v-on:click="globalHelper">Click me</div>

Chafik Gharbi Full-stack web and mobile app developer with JavaScript.