Vue原理实现

3/23/2022 programming

# 使用Proxy实现简单的数据绑定

查看答案
<div id="app">
    <input type="text" id="input">
    <div> TODO: <span id="text"></span> </div>
    <div id="btn">Add To Todo List</div>
    <ul id="list"></ul>
</div>
1
2
3
4
5
6
const input = document.getElementById('input')
const text = document.getElementById('text')
const list = document.getElementById('list')
const btn = document.getElementById('btn')
let render
const inputObj = new Proxy({}, {
    get(target, key, receiver) {
        return Reflect.get(target, key, receiver)
    },
    set(target, key, value, receiver) {
        if (key === 'text') {
            input.value = value
            text.innerHTML = value
        }
        return Reflect.set(target, key, value, receiver)
    }
})
class Render {
    constructor(arr) {
        this.arr = arr
    }
    init() {
        const fragment = document.createDocumentFragment()
        for (let i = 0; i < this.arr.length; i++) {
            const li = document.createElement('li')
            li.textContent = this.arr[i]
            fragment.appendChild(li)
        }
        list.appendChild(fragment)
    }
    addList(val) {
        const li = document.createElement('li')
        li.textContent = val
        list.appendChild(li)
    }
}
const todoList = new Proxy([], {
    get(target, key, receiver) {
        return Reflect.get(target, key, receiver)
    },
    set(target, key, value, receiver) {
        if (key !== 'length') {
            render.addList(value)
        }
        return Reflect.set(target, key, value, receiver)
    }
})
window.onload = () => {
    render = new Render([]) render.init()
}
input.addEventListener('keyup', e => {
    inputObj.text = e.target.value
})
btn.addEventListener('click', () => {
    todoList.push(inputObj.text)
    inputObj.text = ''
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
更新时间: 2023-01-15 19:59