vue实现数据绑定
Vue 数据绑定的实现方式
Vue 提供了多种数据绑定方式,包括插值表达式、指令绑定和计算属性等。以下是常见的实现方法:
插值表达式
在模板中使用双大括号 {{ }} 绑定数据:
<div>{{ message }}</div>
v-bind 指令 用于绑定 HTML 属性:
<img v-bind:src="imageSrc">
<!-- 简写 -->
<img :src="imageSrc">
v-model 指令 实现表单输入的双向绑定:
<input v-model="message">
v-on 指令 绑定事件监听器:
<button v-on:click="handleClick">点击</button>
<!-- 简写 -->
<button @click="handleClick">点击</button>
计算属性和侦听器
计算属性 用于复杂逻辑计算:

computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}
侦听器 监听数据变化执行异步操作:
watch: {
message(newVal, oldVal) {
console.log('消息变化:', oldVal, '->', newVal)
}
}
响应式原理
Vue 使用 Object.defineProperty (Vue 2) 或 Proxy (Vue 3) 实现数据响应式:
// Vue 2 响应式示例
const data = { message: 'Hello' }
Object.defineProperty(data, 'message', {
get() {
return this._message
},
set(newValue) {
console.log('数据变化')
this._message = newValue
}
})
数组和对象变更检测
Vue 对数组和对象的变更检测有特殊处理:

数组 使用变异方法触发视图更新:
this.items.push(newItem) // 自动触发更新
对象
添加新属性需要使用 Vue.set 或 this.$set:
this.$set(this.someObject, 'newProp', 123)
自定义指令
可以创建自定义指令实现特殊绑定逻辑:
Vue.directive('focus', {
inserted: function(el) {
el.focus()
}
})
使用方式:
<input v-focus>






