Vue响应式原理

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue响应式原理</title>
</head>

<body>
    <h1 v-text="name"></h1>
    <input type="text" v-model="name">
    <h1 v-text="pwd"></h1>
    <input type="text" v-model="pwd">
    <script>
        // 源对象
        let data = {
            name: "hellow",
            pwd: "world"
        }
        // 委托对象
        let $data = {};
        Object.keys(data).forEach(key => {
            def($data, key);
            $data[key] = data[key];
        });
        // 监听属性
        function def(obj, key) {
            let value = "";
            Object.defineProperty(obj, key, {
                enumerable: true,
                configurable: true,
                get: function seter() {
                    return value;
                },
                set: function geter(newVal) {
                    value = newVal;
                    let doms = Array.from(document.getElementsByTagName("*"));
                    doms.forEach(v => {
                        let vt = v.getAttribute("v-text");
                        if (vt === key) {
                            v.textContent = newVal;
                        }

                        let vm = v.getAttribute("v-model");
                        if (vm === key) {
                            v.value = newVal;
                        }
                    })
                }
            });
        }

        // 绑定事件
        let doms = Array.from(document.getElementsByTagName("input"));
        doms.forEach(v => {
            // 是否设置了v-model
            let vm = v.getAttribute("v-model");
            if (vm) {
                v.oninput = function (event) {
                    $data[vm] = event.target.value;
                }

            }
        });
    </script>
</body>

</html>

你可能感兴趣的:(记录,vue.js,node.js,javascript,es6,前端)