javascript / expert
Snippet
Normalizing Reactive Inputs with toValue
Introduced in Vue 3.3, toValue is the successor to unref for composable API design. While unref only unwraps refs, toValue also executes getters. This allows composables to accept a wider range of inputs (static values, refs, or functions returning values) while ensuring the internal logic always works with the current underlying data regardless of how it is wrapped.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { toValue, type MaybeRefOrGetter } from 'vue';function useFeature(source: MaybeRefOrGetter<string>) {// toValue unwraps refs, reactive objects, and executes gettersconst normalized = () => toValue(source);console.log('Current value:', normalized());}// Usage possibilities:useFeature('static');useFeature(ref('reactive'));useFeature(() => 'computed-like');
vue
Breakdown
1
MaybeRefOrGetter<string>
TypeScript utility type representing a raw value, a Ref, or a function returning that value.
2
toValue(source)
Universal unwrap utility that returns the value of a ref or the result of a getter function.