How to use global helper functions in Laravel + Vue 3 (Composition API) + Inertia.js setup

Serdar Cevher
2 min readApr 3, 2022
We often use global helper functions. Get them ready in your Inertia.js + Vue 3 driven templates.

Creators of Vue 3’s Composition API discourage developers from using global variables. But I believe keeping your string helper functions always eligible won’t hurt.

Let’s start by creating a single helpers.js file to put a couple of handy string manipulation functions. (I store this file in the/resources/js/Common path for convenience.)

Now we need to modify the default /resources/app.js file (tailored to work with Laravel 9 + Inertia.js monolith) as seen below. Note that I import the helpers file in the line 7:

As you can see, the $helpers object is added to the app.config.globalProperties in line 24, and this already lets us use any helper method in templates without any further action.

For example, now you can use the “makeReadable” function such as:

<template>
<div>{{ $helpers.makeReadable(‘an_example’) }}</div>
<template>

However, due to the composition API's structural restrictions, we can’t access the app’s global properties in the script block. This is a bit frustrating, and it’s still possible to overcome it by using the getCurrentInstance method, but it’s discouraged in the Vue documentation.

So, what to do? This is the reason why we also included the provide part in the app.js.

We provide helpers to the app as documented in Vue 3 documentation to inject them into any script block whenever needed. This way we make it possible to use helper functions within the script block (in computed properties for example, for conditional usage) as well.

I use <script setup> structure since I find it more convenient, so here’s what I do to get it ready:

<script setup>
import { inject } from 'vue';
const helpers = inject('helpers');
const example = helpers.makeReadable(“an_example”) //“An Example”
</script>

If you do not use the <script setup> syntax, here’s what to do

import { inject } from 'vue';export default {
setup() {
const helpers = inject('helpers');
const example = helpers.makeReadable('an example');

return {
example;
}
}
}

I know that it seems a bit redundant both to use the globalProperties and the provide/inject methods at the same time, but I tried to find the most comfortable solution available.

I wish there would be a way to directly use the global $helpers variable in the script block, yet this is the easiest way I have discovered so far.

Let me know if you have a better way to implement global helper functions for the Laravel + Vue 3 + Inertia.js setup.

--

--

Serdar Cevher

Developer of web & mobile apps | Co-founder: Auglinn, Off2Class | Founder: SmarDish, tarifmotoru.com, valizim.com | Ex columnist @PCnetDergisi