vue-源码-模板解析



//ES6 的class写法
class Vue {

    //构造器
    constructor(options) {
        //生成el
        this.$el = document.querySelector(options.el);

        //生成data

        //函数写法
        if (Object.prototype.toString.call(options.data) === "[object Function]") {
            this.$data = options.data();
            //对象写法
        } else if (Object.prototype.toString.call(options.data) === "[object String]") {
            this.$data = options.data;
        }


        //编译渲染
        this.compile(this.$el)
    }

    compile(node) {

        node.childNodes.forEach((item, index) => {

            //元素节点
            if (item.nodeType === 1) {

                //递归
                this.compile(item);
            }

            //文本节点
            if (item.nodeType === 3) {

                //正则
                let reg = /\{\{(.*?)\}\}/g;

                //textContent属性表示一个节点及其后代的文本内容。
                let text = item.textContent;

                //编写规则
                item.textContent = text.replace(reg, (match, vmKey) => {
                    //去掉两边空格
                    vmKey = vmKey.trim();
                    //替换
                    console.log(this.$data)
                    return this.$data[vmKey]
                })
            }

        })
    }


}
<body>
    <div id="app">

        <h1>{{name}}</h1>
    </div>
</body>

<script>

    let app = new Vue({
        el: '#app',
        data: function () {
            return {
                name: '小明'
            }
        },
        mounted() {
            console.log(this);
        }

    })

</script>

文章作者: iamfugui
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 iamfugui !
评论
  目录