vue 如何实现vmodel
Vue 中实现 v-model 的方法
在 Vue 中,v-model 是一个语法糖,用于在表单元素或自定义组件上实现双向数据绑定。以下是实现 v-model 的几种方式:
在表单元素上使用 v-model
对于原生表单元素(如 input、textarea、select),v-model 会自动绑定 value 属性并监听 input 事件。
<template>
<input v-model="message" placeholder="Edit me" />
<p>Message is: {{ message }}</p>
</template>
<script>
export default {
data() {
return {
message: ''
}
}
}
</script>
在自定义组件上使用 v-model
在自定义组件中,v-model 默认会绑定 value 属性和监听 input 事件。可以通过 model 选项或 Vue 2.2+ 的 v-bind 和 v-on 语法自定义。
方法 1:默认实现
<template>
<custom-input v-model="message"></custom-input>
</template>
<script>
export default {
data() {
return {
message: ''
}
},
components: {
'custom-input': {
props: ['value'],
template: `
<input
:value="value"
@input="$emit('input', $event.target.value)"
/>
`
}
}
}
</script>
方法 2:自定义 prop 和事件
如果需要使用非默认的 value 和 input,可以通过 model 选项配置:
<template>
<custom-input v-model="message"></custom-input>
</template>
<script>
export default {
data() {
return {
message: ''
}
},
components: {
'custom-input': {
model: {
prop: 'text',
event: 'change'
},
props: ['text'],
template: `
<input
:value="text"
@input="$emit('change', $event.target.value)"
/>
`
}
}
}
</script>
Vue 3 中的 v-model 实现
在 Vue 3 中,v-model 的实现有所变化,支持多个 v-model 绑定,并默认使用 modelValue 和 update:modelValue。
自定义组件示例:
<template>
<custom-input v-model="message"></custom-input>
</template>
<script>
export default {
data() {
return {
message: ''
}
},
components: {
'custom-input': {
props: ['modelValue'],
template: `
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
`
}
}
}
</script>
多个 v-model 绑定:
<template>
<custom-input
v-model:first="first"
v-model:second="second"
></custom-input>
</template>
<script>
export default {
data() {
return {
first: '',
second: ''
}
},
components: {
'custom-input': {
props: ['first', 'second'],
template: `
<input
:value="first"
@input="$emit('update:first', $event.target.value)"
/>
<input
:value="second"
@input="$emit('update:second', $event.target.value)"
/>
`
}
}
}
</script>
使用计算属性实现高级绑定
如果需要更复杂的逻辑,可以通过计算属性实现:
<template>
<input v-model="computedMessage" />
</template>
<script>
export default {
data() {
return {
message: ''
}
},
computed: {
computedMessage: {
get() {
return this.message
},
set(value) {
this.message = value.toUpperCase()
}
}
}
}
</script>
通过以上方法,可以灵活地在 Vue 中实现 v-model 的双向绑定功能。







