How To Create Global Function In Vue Laravel Application

Hello Artisan,

In this tutorial, I will show you how to create a global function in Laravel application using vue js. Sometimes we need to create a global function to access from every pages in Vue component in Laravel application.

So I am here to show you that how to create a global function in vue Laravel application. If you don't know how to create it then this example is for you. We can do it Using Mixins and Using Plugins.

The way I will show you I think will help you. Let's see the first example with plugins:

resources/js/config.js

const Config = {
    install(Vue, options) {
        
      Vue.prototype.getAppPathForImageUrl = () => {
        return 'http://127.0.0.1:8000/public/storage/';
      }

      Vue.prototype.getAppPath = () => {
        return 'http://127.0.0.1:8000/';
      }

    },
}

Vue.use(Config)

 

Now include it in app.js file like:

resources/js/app.js

require('./config');

 

Now we can use it any component like:

 

Now another way is using mixin. So see the below example:

Vue.mixin({
  methods: {
    globalHelper: function () {
      alert("Hello world")
    },
  },
})

 

Now use like:

 

Read also: Vuex Complete Guide with Axios Api Call in Vue Js

 

Hope it can help you.

 

#laravel #laravel-9x #vue-js