Vue Tip: Dynamic Return Values in Composables
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:
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:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Use VueUse to Unleash the Power of Utility Functions
VueUse is a collection of hundreds of essential Vue Composition Utilities for interacting with various browsers, sensors, animations, and state APIs, and more.
Vue Tip: Manually Stop Watcher
You need to manually stop your Vue watcher if they are created asynchronously. Sync watchers are automatically stopped when the component is unmounted.