美文网首页
vue-数据双向绑定实现

vue-数据双向绑定实现

作者: Mokingc | 来源:发表于2019-11-21 16:02 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>双向绑定</title>
</head>
<body>
    <div id="app">
        <input type="text" v-model="name"><br>
        姓名: {{name}}<br>
        <input type="text" v-model="age"><br>
        年龄: {{age}}
    </div>
</body>
<script>
    let el = document.getElementById('app')

    let template = el.innerHTML

    let _data = {
        name: 'blue',
        age: 18,
    }

    let data = new Proxy(_data,{
        set(obj,name,value){
            obj[name] = value
            console.log('数据改了')

             render();
        }
    })
    
    render();

    function render(){
        el.innerHTML = template.replace(/\{\{\w+\}\}/g,str=>{
            str = str.substring(2,str.length-2)

            return _data[str]
        })


        //找所以的v-model
        Array.from(el.getElementsByTagName('input'))
            .filter(ele=>ele.getAttribute('v-model'))
            .forEach(input=>{
                let name = input.getAttribute('v-model')
                input.value = _data[name]

                input.oninput= function(){
                    data[name] = this.value
                }
            })
    }
</script>
</html>

相关文章

网友评论

      本文标题:vue-数据双向绑定实现

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