vue中实现双向绑定
Vue 双向绑定的实现方式
Vue 中实现双向绑定主要通过 v-model 指令,它结合了属性绑定和事件监听,适用于表单元素和自定义组件。
表单元素的双向绑定
在表单元素(如 input、textarea、select)上使用 v-model 可以自动同步数据:
<input v-model="message" placeholder="输入内容">
<p>输入的内容是: {{ message }}</p>
data() {
return {
message: ''
}
}
v-model 会根据输入类型自动选择更新数据的方式:
text和textarea使用value属性和input事件checkbox和radio使用checked属性和change事件select使用value属性和change事件
自定义组件的双向绑定
在自定义组件中实现双向绑定需要显式定义 model 选项并触发更新事件:
<custom-input v-model="message"></custom-input>
// 子组件
Vue.component('custom-input', {
props: ['value'],
template: `
<input
:value="value"
@input="$emit('input', $event.target.value)"
>
`
})
Vue 2.x 中也可以通过 .sync 修饰符实现双向绑定:
<child-component :title.sync="pageTitle"></child-component>
子组件需要显式触发更新事件:
this.$emit('update:title', newValue)
原理说明
Vue 的双向绑定本质是语法糖,结合了:
- 属性绑定(
:value="value") - 事件监听(
@input="value = $event.target.value")
在底层实现上,Vue 通过数据劫持(Object.defineProperty)或 Proxy(Vue 3)监听数据变化,结合发布-订阅模式更新视图。
注意事项
- 对于复杂对象,Vue 可能无法检测到属性的添加或删除,需要使用
Vue.set或this.$set - 在 Vue 3 中,
v-model默认使用modelValue作为 prop,update:modelValue作为事件 - 多个双向绑定可以通过参数指定,如
v-model:title="pageTitle"







