carpediem
carpediem
NNuxt
Created by carpediem on 7/4/2024 in #❓・help
Load composable on-demand
Hello everyone, Some of my composables use a bunch of dependencies and to alleviate the dependencies required at startup I want to load the composables in question on demand only. That's why I've set this up (please see code below). Before I wasn't using nuxtApp.runWithContext (please see code), but was getting lots of errors about the nuxt instance not being available. Do you see any problems with the way we do things? Do you know of an easier and/or more effective way? Thanks in advance 🙏🏽
// app/shared/ui/composables/abc/useAbcManager

export const useAbcManager = () => {
return {
"method1": () => {},
"method2": () => {},
}
};
// app/shared/ui/composables/abc/useAbcManager

export const useAbcManager = () => {
return {
"method1": () => {},
"method2": () => {},
}
};
// app/shared/ui/composables/abc/useAbcManagerLoader

/**
* I allow to load the composable on-demand only
*/
export const useAbcManagerLoader = async () => {
return (
await import("~/app/shared/ui/composables/abc/useAbcManager")
).useAbcManager();
};
// app/shared/ui/composables/abc/useAbcManagerLoader

/**
* I allow to load the composable on-demand only
*/
export const useAbcManagerLoader = async () => {
return (
await import("~/app/shared/ui/composables/abc/useAbcManager")
).useAbcManager();
};
// app/pages/index.vue

<script setup lang="ts">
const method1 = async () =>
await nuxtApp.runWithContext(
async () => (await useAbcManagerLoader()).method1,
);
</script>
// app/pages/index.vue

<script setup lang="ts">
const method1 = async () =>
await nuxtApp.runWithContext(
async () => (await useAbcManagerLoader()).method1,
);
</script>
9 replies