一、回顾vue响应式用法

​ vue响应式,我们都很熟悉了。当我们修改vue中data对象中的属性时,页面中引用该属性的地方就会发生相应的改变。避免了我们再去操作dom,进行数据绑定。

二、vue响应式实现分析

对于vue的响应式原理,官网上给了出文字描述 。

vue内部主要是通过数据劫持和观察者模式实现的

数据劫持:

vue2.x内部使用object.defineproperty https://developer.mozilla.org/zh-cn/docs/web/javascript/reference/global_objects/object/defineproperty

vue3.x内部使用的proxy https://developer.mozilla.org/zh-cn/docs/web/javascript/reference/global_objects/proxy

观察者模式:

内部成员示意图

各个成员的功能

vue:

把data中的成员注入到vue实例中,并把data中的成员转换为getter和setter

observer:

对data对象中的简单类型数据及对象进行监听,当数据发生变化时通知dep

compiler:

解析每个元素中的指令/差值表达式,并替换成相应的数据

dep:

观察者模式中的通知者,添加观察者,当数据变化时通知观察者

watcher:

每个引用data中的属性的地方都有一个watcher对象,负责更新视图

附:data对象中的属性充当被观察者,引用data对象中属性的地方充当观察者

三、vue响应式源码实现

vue对象实现

功能

  • 负责接受初始化的参数
  • 把data中的属性注入到data实例,转换成getter和setter
  • 调用observer监听data中所有属性的变化
  • 调用compiler解析指令、差值表达式.
class vue{
    constructor(options){
        // 1、通过属性保存穿进来的属性
        this.$options= options||{};
        this.$data= options.data||{};
        this.$el = typeof options.el ==='string' ? document.queryselector(options.el) : options.el;
        // 2、把data参数中的数据转换为getter和setter 挂载到vue实例上
        this._proxydata(this.$data)
        // 3、调用observe对象监视data数据的变化
        new observer(this.$data)
        // 4、调用compiler对象渲染页面
        new compiler(this)
    }
    _proxydata(data){
        if (data&&object.keys(data).length>0){
             for (const key in data) {
                object.defineproperty(this,key,{
                    configurable:true,
                    enumerable:true,
                    get(){
                        return data[key]
                    },
                    set(value){
                        if (data[key]===value) {
                            return;
                        }
                        data[key]=value;
                    }
                })
             }
        }
    }
}

observer对象实现

功能

  • 把data选项中的属性进行数据劫持
  • data中的某个属性也是对象的话,进行递归转换成响应式对象
  • 数据变化发送通知
//数据劫持   class observer {
    constructor(data) {
        this.walk(data)
    }
    walk(data) { 
        //1、判断data是否是对象    
        if (!data || typeof data !== 'object') {     
            return
        }
        //2、循环调用definereactive进行数据劫持
        object.keys(data).foreach(key => {
            this.definereactive(data, key, data[key])
        })
    }
    definereactive(obj, key, val) {
        //创建通知者
        const dep = new dep()
        //使用walk把引用对象中的属性变成响应式的
        this.walk(val)
        const that=this;
        object.defineproperty(obj, key, {
            configurable: true,
            enumerable: true,
            get() {
                //通知者收集观察者
                dep.target && dep.addsub(dep.target)
                return val;
            },
            set(newval) {
                if (newval === val) {
                    return;
                }
                val = newval;
                that.walk(newval)
                //被观察者发生变化的时候,通知者对象给每个观察者发送通知
                dep.notify()
            }
        })
    }
}

compile对象实现

功能

  • 负责编译模板,解析指令、差值表达式
  • 负责页面首次渲染
  • 当数据发生改变后,负责重新渲染视图
//编译器   class compiler {
    constructor(vm) {
        this.el = vm.$el;
        this.vm = vm;
        this.compile(this.el)
    }
    //编译模板 判断节点是文本节点还是元素节点
    compile(el) {
        let childnodes = el.childnodes;
        //处理第一层子节点
        array.from(childnodes).foreach(node => {
            if (this.istextnode(node)) {
                this.compiletext(node)
            } else if (this.iselementnode(node)) {
                this.compileelement(node)
            }
            //如果当前节点还有子节点  递归调用编译指令
            if (node.childnodes && node.childnodes.length) {
                this.compile(node)
            }
        })
    }

    //编译元素节点,处理指令
    compileelement(node) {  
        //遍历所有的指令
        array.from(node.attributes).foreach(attr => {
            //判断是不是指令节点
            if (this.isdirective(attr.name)) {
                const nodename = attr.name;
                const key = attr.nodevalue;
                const directive = nodename.substr(2)
                this.updater(directive,node,key)
            }
        }) 
    }
    updater(directive,node,key){
        const updaterfn = this[directive+"updater"]
        updaterfn && updaterfn.call(this,node,this.vm[key],key)
    }
    //v-text
    textupdater(node,value,key){
        node.textcontent=value
        //使用v-text表达式的地方就是一个观察者
        new watcher(this.vm,key,newvalue => {
            node.textcontent = newvalue
        })
    }
    //v-model
    modelupdater(node,value,key){
        node.value =value
        //使用v-model表达式的地方就是一个观察者
        new watcher(this.vm,key,newvalue => {
            node.value = newvalue
        })
      //实现双向绑定
        node.addeventlistener('input',()=>{
            this.vm[key] = node.value
        })
    }
    //v-html
    htmlupdater(node,value,key){
        node.innerhtml = value
        //使用v-html表达式的地方就是一个观察者
        new watcher(this.vm,key,newvalue => {
            node.innerhtml = newvalue
        })
    }

    //处理差值表达式
    compiletext(node) {
        //匹配差值表达式的正则
        let reg = /\{\{(.+?)\}\}/
        //用正则匹配node的textcontent,如果匹配到了 就替换
        if (reg.test(node.textcontent)) {
            //获取插值表达式的key
            let key = regexp.$1;
            let value = node.textcontent;
            node.textcontent = value.replace(reg, this.vm[key])

            //使用差值表达式的地方就是一个观察者
            new watcher(this.vm,key,newvalue => {
                node.textcontent = newvalue
            })
        }
    }

    //是否是指令
    isdirective(attrname) {
        return attrname.startswith('v-')
    }

    //是否是文本节点
    istextnode(node) {
        return node.nodetype === 3
    }

    //是否是元素
    iselementnode(node) {
        return node.nodetype === 1
    }
}

dep对象实现

功能

  • 收集依赖,添加观察者
  • 通知所有观察者
//通知者类   class dep {
    constructor() {
        //存储观察者
        this.subs = []
    }

    /**
     * 收集观察者
     */
    addsub(sub) {
        if (sub && sub.update) {
            this.subs.push(sub)
        }
    }

    /**
     * 通知观察者改变状态
     */
    notify() {
        this.subs.foreach(sub => {
            sub.update()
        })
    }
}

watcher对象实现

功能

  • 当数据变化时,dep通知所有watcher实例更新视图
  • 自身实例化的时候往dep对象中添加自己
//观察者类   class watcher {
    constructor (vm,key,cb) {
        //vue实例
        this.vm =vm;
        // data中的key对象
        this.key =key;
        // 更新视图的回调函数
        this.cb = cb
        //把当前观察者实例存放在dep的target静态属性中
        dep.target =this
        //触发observe的getter方法,把当前实例存放在dep.subs中
        //data中key对应的旧值
        this.oldvalue = this.vm[this.key]
        dep.target = null
    }
    //每个观察者都有一个update方法来改变状态
    update(){
        const newvalue = this.vm[this.key]
        if ( this.newvalue === this.oldvalue ) {
            return
        }
        this.cb(newvalue)
    }
}

测试

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
    <script src="./js/dep.js"></script>
    <script src="./js/watcher.js"></script>
    <script src="./js/compiler.js"></script>
    <script src="./js/observer.js"></script>
    <script src="./js/vue.js"></script>
</head>
<body>
    <p id="app">
        <h1>差值表达式</h1>
        <h3>{{msg}}</h3>
        <h3>{{count}}</h3>
        <h1>v-text</h1>
        <p v-text='msg'></p>
        <h1>v-model</h1>
        <input type="text" v-model="msg" attr="msg">
        <input type="text" v-model="count">
        <h1>v-html</h1>
        <p v-html="htmltext"></p>
    </p>
    <script>
        let vm = new vue({
            el:"#app",
            data:{
                msg:'信息',
                count:'数量', 
		person:{name:'张三'},
                htmltext:"<p style='color:red'>你好</p>"
            }
        })
    </script>
</body>

到此这篇关于vue2.x响应式简单讲解及示例的文章就介绍到这了,更多相关vue2.x响应式内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!