1functionuseFoo(x: number | Ref<number>) {2const unwrapped = unref(x); // number type3}45const num = 42;6useFoo(num); // 4278const numRef = ref(99);9useFoo(numRef); // 99
实现原理 (packages/reactivity/src/ref.ts)
通过 isRef 工具函数判断是否为 Ref 对象,是则返回封装的值,不是则返回参数本身
1/**2 * Returns the inner value if the argument is a ref, otherwise return the3 * argument itself. This is a sugar function for4 * `val = isRef(val) ? val.value : val`.5 *6 * @example7 * ```js8 * function useFoo(x: number | Ref<number>) {9 * const unwrapped = unref(x)10 * // unwrapped is guaranteed to be number now11 * }12 * ```13 *14 * @paramref - Ref or plain value to be converted into the plain value.15 * @see {@link https://vuejs.org/api/reactivity-utilities.html#unref}16 */17exportfunction unref<T>(ref: MaybeRef<T> | ComputedRef<T> | ShallowRef<T>): T {18returnisRef(ref) ? ref.value : ref19}