Javascript is required
1 min read

Vue Tip: Dynamic Return Values in 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:

1import { useTimestamp } from '@vueuse/core'
3// Use the single return value
4const timestamp = useTimestamp({ offset: 0 })
6// Access object properties by passing "{ controls: true }"
7const { 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:

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