vue实现双向
Vue 实现双向绑定的方法
Vue 的双向绑定主要通过 v-model 指令实现,它结合了 v-bind(属性绑定)和 v-on(事件监听)的功能。以下是几种常见的实现方式:
使用 v-model 指令
v-model 是 Vue 提供的语法糖,可以简化表单元素的双向绑定。

<template>
<input v-model="message" placeholder="输入内容">
<p>输入的内容是:{{ message }}</p>
</template>
<script>
export default {
data() {
return {
message: ''
}
}
}
</script>
自定义组件实现双向绑定
在自定义组件中,可以通过 model 选项和 $emit 实现双向绑定。
<template>
<custom-input v-model="inputValue"></custom-input>
<p>绑定的值:{{ inputValue }}</p>
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
components: {
'custom-input': {
props: ['value'],
model: {
prop: 'value',
event: 'input'
},
template: `
<input
:value="value"
@input="$emit('input', $event.target.value)"
>
`
}
}
}
</script>
使用 .sync 修饰符
Vue 2.x 中可以通过 .sync 修饰符实现父子组件的双向绑定。

<template>
<custom-input :value.sync="syncValue"></custom-input>
<p>同步的值:{{ syncValue }}</p>
</template>
<script>
export default {
data() {
return {
syncValue: ''
}
},
components: {
'custom-input': {
props: ['value'],
template: `
<input
:value="value"
@input="$emit('update:value', $event.target.value)"
>
`
}
}
}
</script>
Vue 3 中的 v-model 改进
Vue 3 对 v-model 进行了优化,支持多个 v-model 绑定。
<template>
<custom-input v-model:firstName="first" v-model:lastName="last"></custom-input>
<p>全名:{{ first }} {{ last }}</p>
</template>
<script>
export default {
data() {
return {
first: '',
last: ''
}
},
components: {
'custom-input': {
props: {
firstName: String,
lastName: String
},
emits: ['update:firstName', 'update:lastName'],
template: `
<div>
<input
:value="firstName"
@input="$emit('update:firstName', $event.target.value)"
>
<input
:value="lastName"
@input="$emit('update:lastName', $event.target.value)"
>
</div>
`
}
}
}
</script>
双向绑定的底层原理
Vue 的双向绑定基于数据劫持和发布-订阅模式:
- 数据劫持:通过
Object.defineProperty(Vue 2)或Proxy(Vue 3)监听数据变化。 - 依赖收集:在 getter 中收集依赖,在 setter 中通知更新。
- 模板编译:将模板解析为渲染函数,建立数据与视图的关联。
- 更新视图:数据变化时触发重新渲染。
// 简化的数据劫持示例(Vue 2)
function defineReactive(obj, key, val) {
Object.defineProperty(obj, key, {
get() {
console.log(`读取 ${key}`);
return val;
},
set(newVal) {
console.log(`设置 ${key} 为 ${newVal}`);
val = newVal;
}
});
}
以上方法覆盖了 Vue 中实现双向绑定的主要场景和技术细节。






