DEV Community

Cover image for Make a Vue3 Composable Globally Accessible with Provide/Inject API
Bilal Haidar
Bilal Haidar

Posted on

Make a Vue3 Composable Globally Accessible with Provide/Inject API

In a Vue 3 application, you can make a composable globally accessible using the provide/inject pattern. This way, you can inject the composable and its functions into your components without importing it explicitly in each component.

If you are new to Provide/Inject API in Vue3, I've got you covered! You can read my introduction on this topic here:

Vue3 Provide/Inject API - Part 1
Vue3 Provide/Inject API - Part 2

Back to our topic on exposing a Composable globally. Let's go through an example:

Create the Composable

Assuming you have a composable named myComposable that returns a function, here's an example:

// myComposable.js
import { ref } from 'vue';

export function useMyComposable() {
  const myFunction = ref(() => {
    // Your function logic here

  return {
Enter fullscreen mode Exit fullscreen mode

Provide the Composable

In your main application file (like main.js or main.ts), provide the composable globally using the provide function:

// main.js
import { createApp } from 'vue';
import App from './App.vue';
import { useMyComposable } from './path/to/myComposable';

const app = createApp(App);

const myComposable = useMyComposable();
app.provide('myComposable', myComposable);

Enter fullscreen mode Exit fullscreen mode

Inject the Composable in Components

Now, in any component where you want to use the composable, you can inject it using the inject function:

<script setup>
import { inject } from 'vue';

// Inject the composable
const myComposable = inject('myComposable');

// Now myComposable.myFunction is available for use in this component

    <!-- Use the function from the composable -->
    <button @click="myComposable.myFunction">Invoke Function</button>
Enter fullscreen mode Exit fullscreen mode

By providing the composable at the application level, you can access it in any component without the need to import it explicitly. This follows the global state management pattern using Vue 3's provide and inject.

Top comments (0)