当前位置:首页 > VUE

vue实现双向绑定代码

2026-02-24 05:39:34VUE

Vue 2 实现双向绑定

Vue 2 使用 v-model 指令实现双向绑定,主要基于 Object.defineProperty 实现数据劫持。

<template>
  <div>
    <input v-model="message" placeholder="输入内容">
    <p>输入的内容是: {{ message }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: ''
    }
  }
}
</script>

自定义组件中实现双向绑定:

<template>
  <custom-input v-model="message"></custom-input>
</template>

<script>
export default {
  components: {
    'custom-input': {
      props: ['value'],
      template: `
        <input
          :value="value"
          @input="$emit('input', $event.target.value)"
        >
      `
    }
  },
  data() {
    return {
      message: ''
    }
  }
}
</script>

Vue 3 实现双向绑定

Vue 3 使用 v-model 指令,底层基于 Proxy 实现响应式。

<template>
  <input v-model="message" placeholder="输入内容">
  <p>输入的内容是: {{ message }}</p>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const message = ref('')
    return { message }
  }
}
</script>

自定义组件中实现双向绑定:

<template>
  <custom-input v-model="message"></custom-input>
</template>

<script>
import { ref } from 'vue'

export default {
  components: {
    'custom-input': {
      props: ['modelValue'],
      emits: ['update:modelValue'],
      template: `
        <input
          :value="modelValue"
          @input="$emit('update:modelValue', $event.target.value)"
        >
      `
    }
  },
  setup() {
    const message = ref('')
    return { message }
  }
}
</script>

手动实现简易双向绑定

以下是一个基于 Object.defineProperty 的简易实现:

function defineReactive(obj, key) {
  let value = obj[key]
  const dep = new Dep()

  Object.defineProperty(obj, key, {
    get() {
      if (Dep.target) {
        dep.addSub(Dep.target)
      }
      return value
    },
    set(newVal) {
      if (newVal === value) return
      value = newVal
      dep.notify()
    }
  })
}

class Dep {
  constructor() {
    this.subs = []
  }
  addSub(sub) {
    this.subs.push(sub)
  }
  notify() {
    this.subs.forEach(sub => sub.update())
  }
}

class Watcher {
  constructor(vm, exp, cb) {
    this.vm = vm
    this.exp = exp
    this.cb = cb
    Dep.target = this
    this.value = vm[exp]
    Dep.target = null
  }
  update() {
    const value = this.vm[this.exp]
    if (value !== this.value) {
      this.value = value
      this.cb.call(this.vm, value)
    }
  }
}

使用示例:

const data = { message: 'Hello' }
defineReactive(data, 'message')

new Watcher(data, 'message', value => {
  console.log('值变化:', value)
})

data.message = 'World'  // 控制台输出: 值变化: World

注意事项

Vue 2 中数组和对象需要特殊处理,Vue.set 或 this.$set 用于添加响应式属性

Vue 3 的 Proxy 实现可以自动检测深层对象变化,无需特殊处理

vue实现双向绑定代码

自定义组件中,Vue 2 默认使用 value 属性和 input 事件,Vue 3 使用 modelValue 属性和 update:modelValue 事件

标签: 绑定双向
分享给朋友:

相关文章

怎么用vue.js实现双向绑定

怎么用vue.js实现双向绑定

使用 v-model 指令实现双向绑定 Vue.js 提供了 v-model 指令用于在表单输入元素(如 input、textarea、select)上实现双向数据绑定。v-model 会根据控件类型…

vue双向绑定实现简单

vue双向绑定实现简单

Vue 双向绑定的简单实现 双向绑定的核心是通过数据劫持结合发布-订阅模式实现。以下是简化版的实现步骤: 数据劫持(Object.defineProperty) 通过 Object.definePr…

php实现双向队列

php实现双向队列

PHP 实现双向队列的方法 双向队列(Deque,Double-ended Queue)是一种允许在队列两端进行插入和删除操作的数据结构。PHP 中可以通过数组或 SplDoublyLinkedLis…

vue实现数组绑定

vue实现数组绑定

Vue 数组绑定的实现方法 Vue 提供了多种方式实现数组的响应式绑定,确保数据变化时视图自动更新。以下是常见的实现方法: 使用 v-for 指令渲染数组 通过 v-for 指令可以遍历数组并渲染…

vue双向实现原理

vue双向实现原理

Vue 双向数据绑定的实现原理 Vue 的双向数据绑定主要通过数据劫持结合发布-订阅模式实现,核心是 Object.defineProperty(Vue 2.x)或 Proxy(Vue 3.x)。…

vue双向绑定实现

vue双向绑定实现

Vue 双向绑定实现原理 Vue 的双向绑定主要通过 v-model 指令实现,其核心是结合数据劫持(Object.defineProperty 或 Proxy)和发布-订阅模式。 数据劫持 Vue…