模擬實現vue數據雙向綁定

<body>
    <input type="text" id="input" value=''>
    <h1 id="text"></h1>
    <button id="btn">點擊</button>
</body>
/* 簡單模仿實現vue v-model */
    var obj = {
        "value":9999
    };
    var i = 1;
    const input = document.getElementById('input');
    const text = document.getElementById('text');
    input.value = obj.value;
    text.innerHTML = obj.value;
    input.addEventListener('input',ev => {
        obj.value = input.value;
        i = 1;
    })
    Object.defineProperty(obj,'value',{
        get:() => {
            return
        },
        set:(newVal) => {
            input.value = newVal;
            text.innerHTML = newVal;
        }
    })
    //賦值,驗證值是否更改
    const btn = document.getElementById('btn');
    btn.addEventListener('click',() => {
        obj.value = ''
        obj.value = i++;
    })
相關文章
相關標籤/搜索