Vue front-end development and learning-the principle of Vue two-way data binding ②

The principle of Vue data two-way binding

Core: data broker + publish and subscribe

  • Description: When passing an ordinary JavaScript object to the data option of a Vue instance, Vue will traverse all the properties of this object and use Object.defineProperty to convert all these properties to getter/setter (data hijacking/data mapping). Notify changes when properties are accessed and modified. Each component instance has a corresponding watcher instance object, which will record the attribute as a dependency during the component rendering process, and then when the setter of the dependency is called, it will notify the watcher to recalculate, so that its associated component can be updated .

Object.defineProperty(obj,prop,descriptor)

  • obj: the object whose properties are to be defined
  • prop: the name of the property to be defined or modified
  • descriptor: To define options
<body>
  <div id="app">
    <div id="msg"></div>
    <input type="text" oninput="changeVal(this)">
  </div>
</body>
<script src="./node_modules/vue/dist/vue.js"></script>
<script>
  // 1.定义对象
  let userInfo = {
     
     
    name: "这个信息虽然用户看不到,但是vue可以追踪到",
  }
  // 2.数据劫持
  let obj = {
     
     }
  //要定义属性的对象,要定义或修改的属性的名称,要定义选项
  Object.defineProperty(obj, "name", {
     
     
    get() {
     
     
      return userInfo.name
    },
    set(data) {
     
     
      userInfo.name = data
      document.getElementById("msg").innerHTML = data
      return true
    }
  })
  // 3.实时渲染
  document.getElementById("msg").innerHTML = obj.name

  // 4.发布订阅
  function changeVal(eleObj) {
     
     
    let value = eleObj.value
    obj.name = value
    return true
  }

</script>

Guess you like

Origin blog.csdn.net/weixin_53985543/article/details/115010328