主题
useVModel
v-model 绑定的简写,props+emit->ref
🌐 Shorthand for v-model binding, props + emit -> ref
我们鼓励你使用 Vue 的
defineModel而不是这个组合式,但也有一些边缘情况,例如使用TSX或deep: true选项,而defineModel不支持这些。
用法
🌐 Usage
ts
import { useVModel } from '@vueuse/core'
const props = defineProps<{
modelValue: string
}>()
const emit = defineEmits(['update:modelValue'])
const data = useVModel(props, 'modelValue', emit)js
import { useVModel } from '@vueuse/core'
const props = defineProps()
const emit = defineEmits(['update:modelValue'])
const data = useVModel(props, 'modelValue', emit)选项 API
🌐 Options API
ts
import { useVModel } from '@vueuse/core'
export default {
setup(props, { emit }) {
const data = useVModel(props, 'data', emit)
console.log(data.value) // props.data
data.value = 'foo' // emit('update:data', 'foo')
},
}选项
🌐 Options
被动模式
🌐 Passive Mode
默认情况下,useVModel 返回一个计算属性引用。在被动模式下,它会创建一个本地引用,通过 watch 与 prop 同步,从而实现深度响应式追踪。
🌐 By default, useVModel returns a computed ref. In passive mode, it creates a local ref that syncs with the prop via watch, allowing deep reactivity tracking.
ts
const data = useVModel(props, 'modelValue', emit, { passive: true })深度观察
🌐 Deep Watching
在使用 passive: true 时,你可以启用深度监听来检测嵌套对象的变化:
🌐 When using passive: true, you can enable deep watching for nested object changes:
ts
const data = useVModel(props, 'modelValue', emit, {
passive: true,
deep: true,
})克隆值
🌐 Clone Values
克隆属性值以避免修改原始对象。设置为 true 以使用 JSON.parse(JSON.stringify()),或提供自定义的克隆函数。
🌐 Clone the prop value to avoid mutating the original object. Set to true to use JSON.parse(JSON.stringify()) or provide a custom clone function.
ts
const data = useVModel(props, 'modelValue', emit, {
clone: true,
// or provide custom clone function
// clone: (val) => structuredClone(val),
})默认值
🌐 Default Value
当属性未定义时提供默认值:
🌐 Provide a default value when the prop is undefined:
ts
const data = useVModel(props, 'modelValue', emit, {
defaultValue: 'default',
})自定义事件名称
🌐 Custom Event Name
覆盖默认的 update:propName 事件名称:
🌐 Override the default update:propName event name:
ts
const data = useVModel(props, 'value', emit, {
eventName: 'change',
})发出验证
🌐 Emit Validation
在发出之前使用 shouldEmit 进行验证。返回 false 以阻止发出:
🌐 Use shouldEmit to validate before emitting. Return false to prevent the emit:
ts
const data = useVModel(props, 'modelValue', emit, {
shouldEmit: (value) => {
// Only emit if value is valid
return value.length > 0
},
})