| 18 | options?: DefineModelOptions<T[K], G, S>, |
| 19 | ): ModelRef<T[K], M, G, S> |
| 20 | export function useModel( |
| 21 | props: Record<string, any>, |
| 22 | name: string, |
| 23 | options: DefineModelOptions = EMPTY_OBJ, |
| 24 | ): Ref { |
| 25 | const i = getCurrentInstance()! |
| 26 | if (__DEV__ && !i) { |
| 27 | warn(`useModel() called without active instance.`) |
| 28 | return ref() as any |
| 29 | } |
| 30 | |
| 31 | const camelizedName = camelize(name) |
| 32 | if (__DEV__ && !(i.propsOptions[0] as NormalizedProps)[camelizedName]) { |
| 33 | warn(`useModel() called with prop "${name}" which is not declared.`) |
| 34 | return ref() as any |
| 35 | } |
| 36 | |
| 37 | const hyphenatedName = hyphenate(name) |
| 38 | const modifiers = getModelModifiers(props, camelizedName) |
| 39 | |
| 40 | const res = customRef((track, trigger) => { |
| 41 | let localValue: any |
| 42 | let prevSetValue: any = EMPTY_OBJ |
| 43 | let prevEmittedValue: any |
| 44 | |
| 45 | watchSyncEffect(() => { |
| 46 | const propValue = props[camelizedName] |
| 47 | if (hasChanged(localValue, propValue)) { |
| 48 | localValue = propValue |
| 49 | trigger() |
| 50 | } |
| 51 | }) |
| 52 | |
| 53 | return { |
| 54 | get() { |
| 55 | track() |
| 56 | return options.get ? options.get(localValue) : localValue |
| 57 | }, |
| 58 | |
| 59 | set(value) { |
| 60 | const emittedValue = options.set ? options.set(value) : value |
| 61 | if ( |
| 62 | !hasChanged(emittedValue, localValue) && |
| 63 | !(prevSetValue !== EMPTY_OBJ && hasChanged(value, prevSetValue)) |
| 64 | ) { |
| 65 | return |
| 66 | } |
| 67 | const rawProps = i.vnode!.props |
| 68 | const hasVModel = !!( |
| 69 | rawProps && |
| 70 | // check if parent has passed v-model |
| 71 | (name in rawProps || |
| 72 | camelizedName in rawProps || |
| 73 | hyphenatedName in rawProps) && |
| 74 | (`onUpdate:${name}` in rawProps || |
| 75 | `onUpdate:${camelizedName}` in rawProps || |
| 76 | `onUpdate:${hyphenatedName}` in rawProps) |
| 77 | ) |