关于Vue的双向数据绑定原理(二)

<body>
   <input type="text" v-model='content'>
    <h4 v-bind="content"></h4>
    <hr/>
    <input type="text" v-model='title'>
    <input type="text" v-model='title'>
    <h4 v-bind="title">这里会更新</h4>
</body>

实现页面影响数据

    // 首先实例化一个代理Proxy
    let proxy = new Proxy({}, {
        get(obj, property) {
          
        },
        set(obj, property, value) {
            document.querySelectorAll(`[v-model="${property}"]`).forEach(i=>{
               i.value=value
           })
           document.querySelectorAll(`[v-bind="${property}"]`).forEach(i=>{
               i.innerHTML=value
           })
        }
    })

    //获取绑定元素
    const els = document.querySelectorAll("[v-model]") 
    //遍历+keyup键盘抬起绑定
    els.forEach(i => {
        i.addEventListener("keyup", function () {
            // 标签的v-model属性值 = this.value值
            proxy[this.getAttribute("v-model")] = this.value
        })
    })
实现效果

完整封装代码

    function View(){
        let proxy = new Proxy({},{
            get(obj,property){
            },
            set(obj,property,value){
                document.querySelectorAll(`[v-model="${property}"]`).forEach(i=>{
                    i.value = value
                })
                document.querySelectorAll(`[v-bind="${property}"]`).forEach(i=>{
                    i.innerHTML = value
                })
            }

        })
        this.init = function(){
            const els = document.querySelectorAll("[v-model]")
            els.forEach(i=>{
                i.addEventListener("keyup",function(){
                    proxy[this.getAttribute("v-model")] = this.value
                })
            })
        }
    }
    new View().init()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容