深入 vue

2020-03-15  本文已影响0人  iCherries

一、原理

1.渲染

class Cue {
    constructor(options) {
        this.$el = document.querySelector(options.el);
        this.$data = options.data;

        this._render();
    }

    _render() {
        const renderEle = node => {
            Array.from(node.childNodes).forEach(el => {
                switch (el.nodeType) {
                    case document.ELEMENT_NODE: //1
                        renderEle(el);
                        break;
                    case document.TEXT_NODE: // 3
                        el.data = el.data.replace(/\{\{\w+\}\}/g, str => {
                            const name = str.substring(2, str.length - 2);
                            return this.$data[name];
                        });
                }
            });
        };

        renderEle(this.$el);
    }
}

const cm = new Cue({
    el: "#root",
    data: {
        name: "cherries",
        age: 18
    }
});

2.双向绑定

<div id="root">
    <input type="text" v-model="name" /> <input type="text" v-model="name" />
    <br />
    <input type="text" v-model="age" /> <input type="text" v-model="age" />
    <br />
</div>
<script>
    let _person = {
        name: "cherries",
        age: 18
    };

    let person = new Proxy(_person, {
        get(obj, name) {
            return obj[name];
        },
        set(obj, name, value) {
            obj[name] = value;
            dataToHtml();
        }
    });

    let aTxt = Array.from(document.querySelectorAll("#root input"));

    // 初始化
    dataToHtml();

    aTxt.forEach(oTxt => {
        oTxt.oninput = () => {
            htmlToData(oTxt);
        };
    });

    function htmlToData(oTxt) {
        const name = oTxt.getAttribute("v-model");
        person[name] = oTxt.value;
    }

    function dataToHtml() {
        aTxt.forEach(oTxt => {
            const name = oTxt.getAttribute("v-model");
            console.log(person[name]);
            oTxt.value = person[name];
        });
    }
</script>
//  v-model  ===   :value + @input

二、computed 计算属性

computed: {
    // name() {},
    name: { // 命名和 data 中的不能一样 
        get() {
        },
        set() {
        }
    }
}

三、watch 监听值得变化(注意: 不要在 watch 中修改数据)

watch: {
    name() {}, // 名字和监听的变量名称一样
    'obj.key'() {},

}

vm.$watch('json', (newVal, oldVal) => {}, { deep: true }) // deep 是否深层监视  
上一篇下一篇

猜你喜欢

热点阅读