Skip to content

useVModel

v-model 的快捷绑定,将 props + emit 合并为一个可写 ref。


函数签名

ts
// 主动模式(默认):返回 WritableComputedRef
function useVModel<P, K extends keyof P>(
  props: P,
  key?: K,
  emit?: (name: string, ...args: any[]) => void,
  options?: UseVModelOptions<P[K], false>,
): WritableComputedRef<P[K]>

// 被动模式:返回 Ref,通过 watch 同步
function useVModel<P, K extends keyof P>(
  props: P,
  key?: K,
  emit?: (name: string, ...args: any[]) => void,
  options?: UseVModelOptions<P[K], true>,
): Ref<UnwrapRef<P[K]>>

基础用法

参数

参数说明类型默认值
props组件的 props 对象P
keymodel 属性名K extends keyof P'modelValue'
emit组件的 emit 函数(name: string, ...args: any[]) => void
options配置项UseVModelOptions{}

UseVModelOptions

参数说明类型默认值
passive被动模式,使用 watch 同步而非 computedbooleanfalse
eventName自定义 emit 事件名string'update:${key}'
deep深度监听(仅 passive 模式)booleanfalse
defaultValue无值时的默认值T
clone是否克隆 props 值,true 使用 JSON 深拷贝boolean | CloneFn<T>false
shouldEmit触发 emit 前的钩子,返回 false 阻止 emit(v: T) => boolean

返回值

  • 主动模式(passive=false):WritableComputedRef,get 读取 props 值,set 触发 emit
  • 被动模式(passive=true):Ref,通过 watch 双向同步

代码示例

vue
<!-- 子组件 -->
<script setup>
import { useVModel } from 'ljf-hooks'

const props = defineProps<{ modelValue: number }>()
const emit = defineEmits(['update:modelValue'])

// 直接修改 data 会自动触发 emit('update:modelValue', value)
const data = useVModel(props, 'modelValue', emit)
</script>

<template>
  <button @click="data++">{{ data }}</button>
</template>