Jiří ProcházkaArticles

Jiří Procházka Articles

VueNuxt#frontend

Two types of composables

2 months ago - 7 min read #vue, #nuxt

Here I'm going to describe how I see the composables in Vue apps.
There are two types of composables:

  • Functional
  • Business logic

But let's start with a description what composable is.

Composables

I will help myself with Vue documentation here:

In the context of Vue applications, a "composable" is a function that leverages Vue's Composition API to encapsulate and reuse stateful logic.

In contrast, when you need som simple stateless function like formatting date, it should go to some utils or lib folder and it is not a composable.

Functional Composables

Among functional composables I reckon functionality that do some technical stuff from the application point of view. A great example is a Nuxt useFetch.

It serves its purpose which is not related to the application business logic. In such cases I tend to use a default export.

const fetch = useFetch("/api/users");
// or
// an object decomposition, not a named export
const { data, errror } = useFetch("/api/users"); 

Business Logic Composables

On the other hand composables I warp the business logic into are Business Logic Composables and mostly I export them with named export.

When it is a small application I make one composable per one use case, like useCreateUser.
In case of bigger application I group domain logic into one composable:

const { createUser, getUsers } = useUsers();

Default Export vs. Named Exports

I'm trying to follow the pattern of default exports for functional composables vs. named exports for business logic composables, but it is just a rule of thumb. There are many exceptions to that and at the end it is up to every team how they setup their coding standards.

Jiří Procházka Newsletter

Want to get new tips for Vue & Nuxt?