vue实现v-mode
Vue 实现 v-model
在 Vue 中,v-model 是一个语法糖,用于在表单元素或组件上实现双向数据绑定。以下是几种实现方式:
在表单元素上使用 v-model
v-model 可以直接用于原生表单元素(如 input、textarea、select),它会根据元素类型自动绑定对应的属性和事件。
<input v-model="message" placeholder="请输入内容">
<p>输入的内容是:{{ message }}</p>
data() {
return {
message: ''
}
}
在自定义组件上实现 v-model
在自定义组件中,v-model 默认会绑定 value 属性和 input 事件。可以通过 model 选项修改默认行为。
<custom-input v-model="message"></custom-input>
Vue.component('custom-input', {
props: ['value'],
template: `
<input
:value="value"
@input="$emit('input', $event.target.value)"
>
`
})
使用 model 选项自定义属性和事件
如果需要绑定其他属性或事件,可以通过 model 选项指定。
Vue.component('custom-input', {
model: {
prop: 'text',
event: 'change'
},
props: ['text'],
template: `
<input
:value="text"
@input="$emit('change', $event.target.value)"
>
`
})
使用 .sync 修饰符实现双向绑定
Vue 2.3.0+ 支持 .sync 修饰符,可以实现父子组件间的双向绑定。
<custom-input :text.sync="message"></custom-input>
Vue.component('custom-input', {
props: ['text'],
template: `
<input
:value="text"
@input="$emit('update:text', $event.target.value)"
>
`
})
Vue 3 中的 v-model 变化
在 Vue 3 中,v-model 的默认行为改为绑定 modelValue 属性和 update:modelValue 事件。
<custom-input v-model="message"></custom-input>
app.component('custom-input', {
props: ['modelValue'],
template: `
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
>
`
})
多个 v-model 绑定
Vue 3 支持在单个组件上绑定多个 v-model。

<custom-input v-model:first="first" v-model:last="last"></custom-input>
app.component('custom-input', {
props: ['first', 'last'],
template: `
<input
:value="first"
@input="$emit('update:first', $event.target.value)"
>
<input
:value="last"
@input="$emit('update:last', $event.target.value)"
>
`
})






