Home  >  Article  >  Web Front-end  >  Let's talk about how to implement two-way data binding in Vue

Let's talk about how to implement two-way data binding in Vue

青灯夜游
青灯夜游forward
2022-11-24 21:15:191584browse

How to implement two-way data binding in

Vue? The following article will introduce to you the implementation method of Vue.js data two-way binding. I hope it will be helpful to you!

Let's talk about how to implement two-way data binding in Vue

When we use vue, when the data changes, the interface will also be updated, but this is not a matter of course. How does vue listen when we modify the data? Data changes and how does Vue refresh the interface when the data changes?

When we modify the data, vue monitors the data changes through the Object.defineProperty method in es5. When the data changes, it uses the publish and subscribe mode The statistics subscriber interface has been refreshed, which is a design pattern. [Learning video sharing: vue video tutorial, web front-end video]

As shown below, starting from new Vue to create a Vue instance, el and data, data will be passed in An observer object will be passed in, and Object.definproperty will be used to convert the data in data into getter/setter for data hijacking. Each property in data will create a Dep instance to save the watcher instance

El is passed into compile, and the instructions are parsed in compile. When the data in data is parsed into el, our getter will be triggered, thereby adding our watcher to the dependency. When the data changes, our setter will be triggered to issue a dependency notification and notify the watcher. After receiving the notification, the watcher will send a notification to the view and let the view update

Lets talk about how to implement two-way data binding in Vue

Data Hijacking

The html part creates a div tag with the id app, which contains span and input tags. The span tag uses interpolation expressions, and the input tag uses v-model

<div class="container" id="app">
    <span>内容:{{content}}</span>
    <input type="text" v-model="content">
</div>

The js part introduces a vue.js file, the code to implement two-way data binding is written in it, then create a Vue instance vm, and mount the data to the div tag

const vm=new Vue({
    el:&#39;#app&#39;,
        data:{
        content:&#39;请输入开机密码&#39;
    }
})

new a Vue instance obviously needs to use the constructor Functions are defined using function in the source code of vue. Here I use ES6’s class to create this Vue instance

and then set constructor, set the formal parameter to obj_instance, as the object passed in when creating a new Vue instance, and assign the data in the passed object to the $data attribute in the instance

In javascript If the properties of the object have changed, you need to tell us so that we can update the changed properties to the dom node. Therefore, when initializing the instance, define a listening function as a call, and when calling, pass in the data that needs to be monitored

class Vue{//创建Vue实例
  constructor(obj_instance){
    this.$data=obj_instance.data
    Observer(this.$data)
  }
}
function Observer(data_instance){//监听函数
  
}

Print this instance vm

Lets talk about how to implement two-way data binding in Vue

The instance has been created but it still needs to be monitored for each attribute in $data. This is used to implement data monitoringObject.defineProperty, Object.defineProperty can modify the existing properties of the object, the syntax format is 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: The property descriptor to be defined or modified

To monitor each property in the object, we use Object.keys and foreach to traverse each property in the object and use Object.defineProperty for each property to monitor data

function Observer(data_instance){
  Object.keys(data_instance).forEach(key=>{
    Object.defineProperty(data_instance,key,{
      enumerable:true,//设置为true表示属性可以枚举
      configurable:true,//设置为true表示属性描述符可以被改变
      get(){},//访问该属性的时候触发,get和set函数就是数据监听的核心
      set(){},//修改该属性的时候触发
    })
  })
}

In Object.defineProperty You need to save the value corresponding to the attribute and then return it in the get function. Otherwise, after reaching the get function, the value of the attribute will be gone, and the value returned to the attribute will become undefined

let value=data_instance[key]
Object.defineProperty(data_instance,key,{
  enumerable:true,
  configurable:true,
  get(){
    console.log(key,value);
    return value
  },
  set(){}
})

Click Clicking the attribute name in $data will trigger the get function

Lets talk about how to implement two-way data binding in Vue

#Then set the set function and set the formal parameter for set. This formal parameter represents the newly passed in attribute value, and then Assign this new attribute value to the variable value. There is no need to return anything, just make modifications. The return is returned when accessing get. After modification, get will also access the latest value variable value

set(newValue){
    console.log(key,value,newValue);
    value = newValue
}

Lets talk about how to implement two-way data binding in Vue

But currently only get and set are set for the first layer attribute of $data. If there is a deeper layer such as

obj:{
    a:&#39;a&#39;,
    b:&#39;b&#39;
}

, get and set are not set. We need to carry out data hijacking into the attributes layer by layer, so we use recursion to monitor ourselves again and make conditional judgments before traversing. If there are no sub-properties or no objects are detected, we will terminate the recursion

function Observer(data_instance){
  //递归出口
  if(!data_instance || typeof data_instance != &#39;object&#39;) return
  Object.keys(data_instance).forEach(key=>{
    let value=data_instance[key]
    Observer(value)//递归-子属性的劫持
    Object.defineProperty(data_instance,key,{
      enumerable:true,
      configurable:true,
      get(){
        console.log(key,value);
        return value
      },
      set(newValue){
        console.log(key,value,newValue);
        value = newValue
      }
    })
  })
}

There is another detail. If we rewrite the content attribute of $data from a string to an object, this new object does not have get and set

Lets talk about how to implement two-way data binding in Vue

因为我们在修改的时候根本没有设置get和set,因此在set里要调用监听函数

set(newValue){
    console.log(key,value,newValue);
    value = newValue
    Observer(newValue)
}

Lets talk about how to implement two-way data binding in Vue

模板解析

劫持数据后就要把Vue实例里的数据应用带页面上,得要加一个临时内存区域,将所有数据都更新后再渲染页面以此减少dom操作

创建一个解析函数,设置2个参数,一个是Vue实例里挂载的元素,另一个是Vue实例,在函数里获取获取元素保存在实例了的$el里,获取元素后放入临时内存里,需要用到[createDocumentFragment]创建一个新的空白的文档片段

然后把$el的子节点一个一个加到fragment变量里,页面已经没有内容了,内容都被临时存在fragment里了

class Vue{
  constructor(obj_instance){
    this.$data=obj_instance.data
    Observer(this.$data)
    Compile(obj_instance.el,this)
  }
}
function Compile(ele,vm){
  vm.$el=document.querySelector(ele)
  const fragment=document.createDocumentFragment()
  let child;
  while (child=vm.$el.firstChild){
    fragment.append(child)
  }
  console.log(fragment);
  console.log(fragment.childNodes);
}

Lets talk about how to implement two-way data binding in Vue

现在直接把需要修改的内容应用到文档碎片里面,应用后重新渲染,只需修改了fragment的childNodes子节点的文本节点,文本节点的类型是3,可以创建一个函数并调用来修改fragment里的内容

节点里面可能还会有节点,因此判定节点类型是否为3,不是就递归调用这个解析函数

节点类型为3就进行修改操作,但也不行把整个节点的文本都修改,只需修改插值表达式的内容,因此要使用正则表达式匹配,将匹配的结果保存到变量里,匹配的结果是一个数组,而索引为1的元素才是我们需要提取出来的元素,这个元素就是去除了{{}}和空格得到的字符串,然后就可以直接用Vue实例来访问对应属性的值,修改完后return出去结束递归

function Compile(ele,vm){
  vm.$el=document.querySelector(ele) //获取元素保存在实例了的$el里
  const fragment=document.createDocumentFragment() //创建文档碎片
  let child;
  while (child=vm.$el.firstChild){//循环将子节点添加到文档碎片里
    fragment.append(child)
  }
  
  fragment_compile(fragment)
  function fragment_compile(node){ //修改文本节点内容
    const pattern = /\{\{\s*(\S*)\s*\}\}/ //检索字符串中正则表达式的匹配,用于匹配插值表达式
    if(node.nodeType===3){
      const result = pattern.exec(node.nodeValue)
      if(result){
        console.log(&#39;result[1]&#39;)
        const value=result[1].split(&#39;.&#39;).reduce(//split将对象里的属性分布在数组里,链式地进行排列;reduce进行累加,层层递进获取$data的值
          (total,current)=>total[current],vm.$data
        )
        node.nodeValue=node.nodeValue.replace(pattern,value) //replace函数将插值表达式替换成$data里的属性的值
      }
      return 
    }
    node.childNodes.forEach(child=>fragment_compile(child))
  }
  vm.$el.appendChild(fragment) //将文档碎片应用到对应的dom元素里面
}

页面的内容又出来了,插值表达式替换成了vm实例里的数据

Lets talk about how to implement two-way data binding in Vue

Lets talk about how to implement two-way data binding in Vue

订阅发布者模式

虽然进行了数据劫持,和将数据应用到页面上,但是数据发生变动还不能及时更新,还需要实现订阅发布者模式

首先创建一个类用来收集和通知订阅者,生成实例的时候需要有一个数组存放订阅者的信息,一个将订阅者添加到这个数组里的方法和一个通知订阅者的方法,调用这个方法就回去遍历订阅者的数组,让订阅者调用自身的update方法进行更新

class Dependency{
  constructor(){
    this.subscribers=[] //存放订阅者的信息
  }
  addSub(sub){
    this.subscribers.push(sub) //将订阅者添加到这个数组里
  }
  notify(){
    this.subscribers.forEach(sub=>sub.update()) //遍历订阅者的数组,调用自身的update函数进行更新
  }
}

设置订阅者类,需要用到Vue实例上的属性,需要Vue实例和Vue实例对应的属性和一个回调函数作为参数,将参数都赋值给实例

然后就可以创建订阅者的update函数,在函数里调用传进来的回调函数

class Watcher{
  constructor(vm,key,callback){//将参数都赋值给Watcher实例
    this.vm=vm
    this.key=key
    this.callback=callback
  }
  update(){
    this.callback() 
  }
}

替换文档碎片内容的时候需要告诉订阅者如何更新,所以订阅者实例在模板解析把节点值替换内容的时候创建,传入vm实例,exec匹配成功后的索引值1和回调函数,将替换文本的执行语句复制到回调函数里,通知订阅者更新的时候就调用这个回调函数

回调函数里的nodeValue要提前保存,不然替换的内容就不是插值表达式而是替换过的内容

Lets talk about how to implement two-way data binding in Vue

然后就要想办法将订阅者存储到Dependency实例的数组里,我们可以在构造Watcher实例的时候保存实例到订阅者数组里

Dependency.temp=this //设置一个临时属性temp

将新的订阅者添加到订阅者数组里且还要将所有的订阅者都进行同样的操作,那么就可以在触发get的时候将订阅者添加到订阅者数组里,为了正确触发对应的属性get,需要用reduce方法对key进行同样的操作

Lets talk about how to implement two-way data binding in Vue

Lets talk about how to implement two-way data binding in Vue

可以看到控制台打印出了Wathcer实例,每个实例都不同,都对应不同的属性值

Lets talk about how to implement two-way data binding in Vue

Dependency类还没创建实例,里面的订阅者数组是不存在的,所以要先创建实例再将订阅者添加到订阅者数组里

Lets talk about how to implement two-way data binding in Vue

Lets talk about how to implement two-way data binding in Vue

修改数据的时候通知订阅者来进行更新,在set里调用dependency的通知方法,通知方法就会去遍数组,订阅者执行自己的update方法进行数据更新

Lets talk about how to implement two-way data binding in Vue

但是update调用回调函数缺少设定形参,依旧使用split和reduce方法获取属性值

update(){
    const value =this.key.split(&#39;.&#39;).reduce(
        (total,current)=>total[current],this.vm.$data
    )
    this.callback(value)
}

在控制台修改属性值都修改成功了,页面也自动更新了

Lets talk about how to implement two-way data binding in Vue

完成了文本的绑定就可以绑定输入框了,在vue里通过v-model进行绑定,因此要判断哪个节点有v-model,元素节点的类型是1,可以使用nodeName来匹配input元素,直接在判断文本节点下面进行新的判断

if(node.nodeType===1&&node.nodeName===&#39;INPUT&#39;){
    const attr=Array.from(node.attributes)
    console.log(attr);
}

节点名字nodeName为v-model,nodeValue为name,就是数据里的属性名

Lets talk about how to implement two-way data binding in Vue

因此对这个数组进行遍历,匹配到了v-model根据nodeValue找到对应的属性值,把属性值赋值到节点上,同时为了在数据更新后订阅者知道更新自己,也要在INPUT节点里新增Watcher实例

attr.forEach(i=>{
    if(i.nodeName===&#39;v-model&#39;){
        const value=i.nodeValue.split(&#39;.&#39;).reduce(
            (total,current)=>total[current],vm.$data
        )
        node.value=value
        new Watcher(vm,i.nodeValue,newValue=>{
            node.value=newValue
        })
    }
})

修改属性值,页面也作出修改

Lets talk about how to implement two-way data binding in Vue

最后剩下用视图改变数据,在v-model的节点上使用addEventListener增加input监听事件就行了

node.addEventListener(&#39;input&#39;,e=>{
    const arr1=i.nodeValue.split(&#39;.&#39;)
    const arr2=arr1.slice(0,arr1.length - 1)
    const final=arr2.reduce(
        (total,current)=>total[current],vm.$data
    )
    final[arr1[arr1.length - 1]]=e.target.value
})

Lets talk about how to implement two-way data binding in Vue

(学习视频分享:web前端开发编程基础视频

The above is the detailed content of Let's talk about how to implement two-way data binding in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete