天天看點

Vue實作資料雙向綁定的兩種方式

第一種是--------------》 資料劫持(Object.defineProperty)

第二種是--------------》 代理(proxy)

面試前準備(ps:被問過一次了)

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>$Title$</title>
</head>
<body>
ES5:Object.defineProperty
<div style="width: 100%;height: 1px;background-color:red;margin-top: 10px"></div>
<br/>
輸入框:<span id="sp"></span>
<br/>
<input type="text" id="ipt" autocomplete="off">
<script>
    let obj = {
        name: ''
    }
    let newObj = {
        ...obj
    }
    Object.defineProperty(obj, 'name', {
        get() {
            return newObj.name
        },
        set(v) {
            newObj.name = v
            observe()
        }
    })

    function observe() {
        sp.innerHTML = newObj.name
    }

    ipt.oninput = function () {
        obj.name = this.value
    }
</script>
<br/><br/>
ES6:Proxy
<br/>
<div style="width: 100%;height: 1px;background-color:red;margin-top: 10px"></div>
<br/>
輸入框:<span id="sp1"></span>
<br/>
<input type="text" id="ipt1">
<script>
    let obj2 = {
        name: ''
    }
    obj2 = new Proxy(obj2, {
        get(target, p) {
            return target[p]
        },
        set(target, p, value) {
            target[p] = value
            observe2()
        }
    })

    function observe2() {
        sp1.innerHTML = obj2.name
    }

    ipt1.oninput = function () {
        obj2.name = this.value
    }
</script>
</body>
</html>
           
Vue實作資料雙向綁定的兩種方式

繼續閱讀