Create Global Helper Function in Laravel Vue Js Application

Hello Artisans, today I'll talk about how you can create a global helper function in your vue js application. Sometimes we need to create a global helper function in vue js for different purposes like getting the base url or convert the currency etc. And it is become quite difficult for us to redeclare in every component. That's why I'm here for you how you can easily create a global helper function and use it in each of every component.

Vue mixin

One of the easiest and handy way is usign mixin. Mixin is the flexible way to distribute the reusable functionalities across all of the available components. For more information see here. So let's see the below example for creating our global helper function. First of all open the main.js/app.js file of your project where you're mounted the vue app.

Now create a file called helper.js and include it in the app.js file like below.

resources/js/app.js
import './bootstrap';

// window.Vue = require('vue');
import Vue from 'vue/dist/vue';
import helper from "./helper.js"

const app = new Vue({
    el: '#app',
    mixins: [helper],
}).$mount('#app');

Now open helper.js file and paste the below code.

resources/js/helper.js
import Vue from 'vue/dist/vue'

export default Vue.mixin({
    data() {
        return {
        }
    },
    mounted() {
    },
    watch: {
    },
    computed: {
    },
    created() {
    },
    methods: {
        getUrl() {
            //use of any link you prefer...it can be hardcoded or by using js
            let base_url = document.querySelector('meta[name="base_url"]').getAttribute('content');
            alert('found the url');
            return base_url;
        },
    }
});

Now we can use it any component as below

resources/js/components/test.vue
<template>
    <section class="section">
        <div class="container mt-5">
            <div class="page-error">
                <div class="page-inner">
                    <div class="page-search">
                        <div class="mt-3">
                            <button @click="getUrl()" class="btn btn-primary btn-lg">{{lang.home}}</router-link>
                        </div>
                    </div>
                </div>
            </div>
            <div class="simple-footer mt-5">

            </div>
        </div>
    </section>
</template>

<script>
export default {
    name: "test",
    mounted() {

    }
}
</script>

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚