简单版vue的双向绑定

我们通过Object.defineProperty( )实现双向数据绑定

方式一:

var ojb = {
     
    content: ''
}

var newObj = ''

Object.defineProperty(ojb, 'content', {
     
    get() {
     
        return newObj
    },
    set(val) {
     
        newObj = val
        observer()
    }
})

function observer() {
     
    content.innerHTML= ojb.content
    ifrom.value = ojb.content
}

ifrom.oninput = function() {
     
    ojb.content = this.value
}

方式二:

var obj = {
     
    content: ''
}

//深拷贝
var newObj = JSON.parse(JSON.stringify(obj))

Object.defineProperty(ojb, 'content', {
     
    get() {
     
        return newObj.content
    },
    set(val) {
     
        newObj.content = val
        observer()
    }
})

function observer() {
     
    content.innerHTML= ojb.content
    ifrom.value = ojb.content
}

ifrom.oninput = function() {
     
    ojb.content = this.value
}

你可能感兴趣的:(笔记)