toValue - VueUse 源码解读

108 阅读1分钟

1、作用

得到value或者ref或者getter的值,这个api在组件设计时很好用,因为组件的props一般都会设计多种传法,某个值可能是一个数组,可能是一个返回数组的函数,另外在设计函数时,也有类似的情况

2、使用案例

export function unrefElement<T extends MaybeElement>(elRef: MaybeComputedElementRef<T>): UnRefElementReturn<T> {
  const plain = toValue(elRef)
  return (plain as VueInstance)?.$el ?? plain
}

3、源码解读

实现比较简单,如果入参是函数时,执行函数,否则使用vue提供的unref这个api得到值

import type { MaybeRefOrGetter, AnyFn } from '../utils'
import { unref } from 'vue'

export function toValue<T>(r: MaybeRefOrGetter<T>): T {
    return typeof r === 'function' ? (r as AnyFn)() : unref(r)
}