javascript / expert
Snippet
Resilient Composables with toValue Normalization
Introduced in Vue 3.3, toValue is a powerful utility that normalizes inputs that could be raw values, refs, or reactive getter functions. This allows composables to be extremely flexible, accepting both static values and dynamic reactive sources without complex logic.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { toValue, watchEffect, ref } from 'vue';export function useDataFetch(source) {const data = ref(null);watchEffect(async () => {const url = toValue(source);const response = await fetch(url);data.value = await response.json();});return { data };}
vue
Breakdown
1
toValue(source)
Unwraps the input regardless of whether it is a Ref, a reactive function (getter), or a plain value.