Vue数据双向绑定

数据双向绑定:数据变化更新视图,视图变化更新数据。

v-modelVue中用来进行数据双向绑定的一个指令,其原理是数据劫持和发布订阅者模式的结合。实现数据双向绑定主要有4个步骤。

  • Observe数据劫持,遍历对象中的所有属性(包括深层嵌套的属性),为它们添加上gettersetter方法用于监听数据变换。使用Object.defineProperty实现,Vue3中使用Proxy实现。

    将一个属性的值改写为对象时也需要进行数据劫持,所以需要重新调用Observe方法。

  • 模板解析。匹配HTML中使用了模板语法的地方,用对应的数据去替换掉使用了模板语法的位置。创建订阅者实例。

  • 发布订阅者模式。定义update方法用于数据变化时更新数据,同时定义一个Dep类用于收集订阅者并且通知订阅者调用update方法更新数据。

  • Observe作为监听器,监视数据Model的变换;Compile用于解析模板,将数据更新到视图上。Watcher作为两者之间的桥梁,负责进行沟通,任意一边进行变换的时候通知另外一边也跟着变化。

//Vue实例类
class Vue{
    constructor(obj_instance){
        this.$data = obj_instance.data
        Observe(this.$data)//进行数据劫持
        Compile(obj_instance.el, this)
    }
}

//定义数据劫持方法
function Observe(data_instance){
    let dependency = new Dependency()
    if  (!data_instance || typeof data_instance !== 'object')
    Object.keys(data_instance).forEach(key => {
        let value = data_instance[key]
        Observe(value)//递归调用,确保嵌套的属性也能被劫持
        Object.defineProperty(data_instace, key, {
            enumerable: true,
            configurable: true,
            get(){
                Dependency.temp && dependency.addSub(Dependency.temp)
                return value
            },
            set(newValue){
                value = newValue
                Observe(newValue)//属性被修改为一个对象的时候也能进行数据劫持
                dependency.notify()//数据变化通知订阅者
            }
        })
    })
}
//定义模板解析函数
function Compile(element, vm){
    vm.$el = decument.querySelect(element)
    let 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){
            let xxx = node.nodeValue//方便后续使用订阅者模式,提前保存模板语法
            let result_regex = pattern.exec(node.nodeValue)//匹配模板语法
            if(result_regex){
                //应对如name.firstName这种写法的模板语句
                let arr = result_regex[1].split('.')
                const value = arr.reduce((total, current) => total[current], vm.$data)
                node.nodeValue = xxx.replace(pattern, value)
                //解析模板的时候定义好后续进行数据更新的方法,也即添加订阅者,下一个数据更新时就会触发订阅者中的update方法
                new Watcher(vm, result_regex[1], newValue => {
                    node.nodeValue = xxx.replace(pattern, newValue)
                })
            }
            return//递归出口
        }
        //寻找输入框,添加事件监听
        if (node.nodeType === 1 && node.nodeName === 'INPUT'){
            const arr = Array.from(node.attributes)
            arr.forEach(i => {
                if (i.nodeName === 'v-model'){
                    //i.nodeValue就是name和more.like这些v-model指令后的值
                    const value = i.nodeValue.split('.')
                        .reduce((total, current) => total[current], vm.$data)
                    node.value = value
                    new Watcher(vm, i.nodeValue, newValue => {
                        node.value = newValue
                    })
                    node.addEventListener('input', e => {
                        const arr1 = i.nodeValue.split('.')
                        const arr2 = arr1.slice(0, arr1.length - 1)
                        const final = arr2.reduce(
                            (total, current) => total[current], vm.$data
                        )
                        // vm.$data.more['like'] = e.target.value
                        final[arr1[arr1.length - 1]] = e.target.value
                    })
                }
            })
        }
        //递归找出所有的文本类型节点
        node.childNodes.forEach(child => {
            fragment_compile(child)
        })
    }
    //替换原有模板语法
    vm.$el.appendChild(fragment)
}

//发布订阅模式
class Dependency{
    consturctor(){
       this.subcribes = []
    }
    
    addSub(subscribe){
        this.subscribes.push(subscribe)
    }
    
    notify(){
        this.subscribes.forEach(item => item.update())
    }
}

class Watcher{
    constructor(vm, key, callback){
        this.vm = vm
        this.key = key
        this.callback = callback
        //在Dependency中将自己保存起来
        Dependency.temp = this
        //读取属性触发getter,将自身添加到真正的发布者实例中
        key.split('.').reduce((total, current) => total[current], vm.$data)
        //每次添加完就清空属性,防止重复添加
        Dependency.temp = null
    }
    
    update(){
        //获取改变后的属性值
        const value = this.key.split('.').reduce((total, current) => total[current], this.vm.$data)
        //回调函数调用同样的方法更新视图
        this.callback(value)
    }
}

响应式原理和数据双向绑定二者相关但是不相同,我的理解是响应式仅仅是数据流向视图,视图数据的更改不会影响数据层。Vue的响应式原理主要有以下几个步骤。

  • 数据劫持Observer。给data中的每一个属性都添加gettersetterVue2中使用definPropertyVue3中使用Proxy。进行数据劫持的同时新建Dep类别,getter中订阅者加入Dep中的订阅者列表,setter的时候调用Dep中的notify方法通知更新。
  • 模板解析Compiler。匹配模板语法并且解析。解析的时候新建Watcher实例,定义数据的更新方法。
  • 发布订阅模式Dep Watcher。发布者主要包含三个部分,subcribes数组记录订阅者;add方法添加新的订阅者;notify方法通知所有订阅者更新数据。Watcher类主要包含两个部分,将自己暂存于Dep.temp中然后读取数据触发getter将实例添加进订阅者数组中然后清空;update方法调用指定的回调函数更新数据。

当然,实际的响应式系统更加复杂,这个等后续研究源码的时候再看看吧。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容