·
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:

import { useTimestamp } from '@vueuse/core' // Use the single return value const timestamp = useTimestamp({ offset: 0 }) // Access object properties by passing "{ controls: true }" 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
export const useTimestamp = (options = { controls: false }) => { const { controls } = options // Here is your remaining composable logic if (controls) { return { timestamp, pause, resume } } else { return timestamp } }