Javascript is required
Michael Hoffmann LogoMichael Hoffmann

Vue Tip: Dynamic Return Values in Composables

Michael Hoffmann - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Jul 27, 2023
1 min read
|
103 views
Composables
Vue Tip: Dynamic Return Values in Composables Image

Vue Composables can return two types of values: a single value or an object of values. It's also possible to dynamically switch between the two depending on what we want to use the composable for.

VueUse heavily uses this pattern to provide a simple interface for the most common use cases, while still allowing for more advanced use cases.

Let's take a look at an example:

1
import { useTimestamp } from '@vueuse/core'
2
3
// Use the single return value
4
const timestamp = useTimestamp({ offset: 0 })
5
6
// Access object properties by passing "{ controls: true }"
7
const { timestamp, pause, resume } = useTimestamp({ controls: true })

If you only need the timestamp you can use the single return value, but if you need more control you can pass an object with the controls property set to true.

I love that approach as it makes the API very simple to use, but still allows for more advanced use cases.

Let's see how we can implement this pattern in a composable:

useTimestamp.ts
1
export const useTimestamp = (options = { controls: false }) => {
2
const { controls } = options
3
4
// Here is your remaining composable logic
5
6
if (controls) {
7
return { timestamp, pause, resume }
8
} else {
9
return timestamp
10
}
11
}

If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter:

New Vue & Nuxt tips delivered to your inbox:
I will never share any of your personal data.