vue2.0

作者: wrs瑞 | 来源:发表于2021-03-14 13:37 被阅读0次

// 数据监听器

function Observer (obj, vm) {
    if (!obj || typeof(obj) !== 'object')  return
    Object.keys(obj).forEach(function (key) {
        defineReactive (vm, key, obj[key])
    })
}
function defineReactive (obj, key, val) {
    var dep = new Dep()
    Observer(val)  //监听子属性
    Object.defineProperty(obj, key, {
        get: function () {
            if (Dep.target) {
                dep.addSub(Dep.target)
            }
            return val
        },
        set: function (newVal) {
            if (val === newVal) return 
            val = newVal
            //作为发布者发布通知,触发订阅者的更新函数
            dep.notify()
        }
    })
}
// 消息订阅器,收集订阅者
function Dep () {
    this.subs = []
}
Dep.prototype = {
    addSub: function (sub) {
        this.subs.push(sub)
    },
    notify: function () {
        this.subs.forEach(function (sub) {
            sub.update()
        })
    }
}

// 订阅者

function Watcher (vm, node, name, type) {
    Dep.target = this
    this.name = name
    this.node = node
    this.vm = vm
    this.type = type
    this.update()
    Dep.target = null
}
Watcher.prototype = {
    update: function () {
        this.get()
        this.node[this.type] = this.value   // 订阅者执行相应的操作
    },
    // 获取data的属性值
    get: function () {
        this.value = this.vm[this.name]
    }
}

相关文章

网友评论

      本文标题:vue2.0

      本文链接:https://www.haomeiwen.com/subject/jtfekktx.html