vue简版源码 Compile

vue简版源码 Compile

<script src="./mvvm-master/js/compile.js"></script>   // compile 模板解析

Compile

function Compile(el, vm) {
    this.$vm = vm; //this Compile的实例  $vm 是MVVM的实例 (vm)
    // el  ==  "#app"  判断当前用户传递的el属性是元素节点还是选择器,如果是元素节点则直接保存到$el中通,
    //如果不是 则根据选择器 去查找对应的元素 然后保存
    this.$el = this.isElementNode(el) ? el : document.querySelector(el);

    //确定元素是否真正存在
    if (this.$el) {//#app
        this.$fragment = this.node2Fragment(this.$el);

        this.$vm.$options.beforeMounted && this.$vm.$options.beforeMounted();
        this.init();
        this.$el.appendChild(this.$fragment);

        this.$vm.$options.mounted && this.$vm.$options.mounted();
    }
}

Compile.prototype = {
    /**
     * node to fragment 把节点转换成文档碎片
     * @param el
     * @returns {DocumentFragment}
     */
    node2Fragment: function(el) {
        var fragment = document.createDocumentFragment(),//文档碎片
            child;

        // 将原生节点拷贝到fragment
        while (child = el.firstChild) {
            fragment.appendChild(child);
        }

        return fragment;
    },

    /**
     * 初始化
     */
    init: function() {
        //解析所有层次的元素节点
        this.compileElement(this.$fragment);
    },

    /**
     * 解析html元素
     * @param el 元素
     */
    compileElement: function(el) {
        //初始化数据,保存所有子节点   保存this
        var childNodes = el.childNodes,
            me = this;

        //对所有子节点进行递归遍历
        [].slice.call(childNodes).forEach(function(node) {
            //text节点的文本内容
            var text = node.textContent;
            //声明匹配大括号表达式的正则
            var reg = /\{\{(.*)\}\}/; //{{name+{{age}}+phone}} //()非贪婪匹配 ->name+{{age}}+phone
            // var reg = /(.*)/; //{{name}}

            //判断当前节点是不是元素节点
            if (me.isElementNode(node)) {
                //解析指令
                me.compile(node);

                //判断当前元素是否为文本节点 并且 文本节点中是否拥有{{xxx}}
            } else if (me.isTextNode(node) && reg.test(text)) {
                //解析文本(大括号表达式)并且赋值
                me.compileText(node, RegExp.$1); //name

            }
            //如果当前节点还有子节点 那么就需要递归查找所有的子节点是否符合以上条件
            if (node.childNodes && node.childNodes.length) {
                me.compileElement(node);
            }
        });
    },

    //解析指令
    compile: function(node) {//button
        //获取元素中的所有属性节点
        var nodeAttrs = node.attributes,
            me = this;

        //遍历所有属性节点
        [].slice.call(nodeAttrs).forEach(function(attr) {
            var attrName = attr.name;//取出属性名
            if (me.isDirective(attrName)) {//判断当前属性名是否为指令 (根据是否有v-)
                var exp = attr.value;//show //获取指令值
                var dir = attrName.substring(2);//on:click //去掉v- 取出指令名
                // 判断当前指令是否为事件指令(是否有on)
                if (me.isEventDirective(dir)) {

                    // node.addEventListener("dir",exp,false);
                    //为当前元素绑定事件
                    compileUtil.eventHandler(node, me.$vm, exp, dir);
                    // 普通指令
                } else {
                    compileUtil[dir] && compileUtil[dir](node, me.$vm, exp);
                }

                //移除解析完成的指令
                node.removeAttribute(attrName);
            }
        });
    },

    compileText: function(node, exp) {
        compileUtil.text(node, this.$vm, exp);
    },

    isDirective: function(attr) {
        return attr.indexOf('v-') == 0;
    },

    isEventDirective: function(dir) {
        return dir.indexOf('on') === 0;
    },

    /**
     * 判断当前的node是不是元节点节点
     * @param node 节点
     * @returns {boolean}
     */
    isElementNode: function(node) {
        // node =  "#app"
        //node.nodeType 1  element元素
        return node.nodeType == 1;
    },

    /**
     * 判断当前的node是不是文本节点
     * @param node 节点
     * @returns {boolean}
     */
    isTextNode: function(node) {
        return node.nodeType == 3;
    }
};

// 指令处理集合
var compileUtil = {
    //解析v-text指令
    text: function(node, vm, exp) {
        this.bind(node, vm, exp, 'text');
    },

    //解析v-html指令
    html: function(node, vm, exp) {
        this.bind(node, vm, exp, 'html');
    },
    //解析v-model指令
    model: function(node, vm, exp) {
        this.bind(node, vm, exp, 'model');

        var me = this,
            val = this._getVMVal(vm, exp);
        node.addEventListener('input', function(e) {
            var newValue = e.target.value;
            if (val === newValue) {
                return;
            }

            me._setVMVal(vm, exp, newValue);
            val = newValue;
        });
    },
    //解析v-class指令
    class: function(node, vm, exp) {
        this.bind(node, vm, exp, 'class');
    },
    //解析v-bind指令
    bind: function(node, vm, exp, dir) {
        //根据指令名称获取对应的更新函数
        var updaterFn = updater[dir + 'Updater'];

        //如果更新函数存在 则执行更新
        // updaterFn && updaterFn(node, this._getVMVal(vm, exp));
        if(updaterFn){
            //node 当前的文本节点, 值  name

            //updaterFn ==> node #text {{name}}  _data.name
            // updaterFn(node, this._data.name);

            updaterFn(node, this._getVMVal(vm, exp));

        }

        //Watcher监听者   vm实例  exp表达式{{a}}/v-text="a"
        new Watcher(vm, exp, function(value, oldValue) {
            updaterFn && updaterFn(node, value, oldValue);
        });
    },

    // 事件处理
    eventHandler: function(node, vm, exp, dir) {//dir==>on:click  exp==>"show"
        //从指令名中取出事件名
        //根据指令的值(表达式)从methods中得到对应的回调函数
        var eventType = dir.split(':')[1],
            fn = vm.$options.methods && vm.$options.methods[exp];

        if (eventType && fn) {
            //给当前元素节点绑定指定的事件名和回调函数(指定this指向为vm)
            node.addEventListener(eventType, fn.bind(vm), false);
        }
    },
    //获取vm中data里相对应的属性值
    _getVMVal: function(vm, exp) {
        //vm => $vm    exp==>"name"  "age.a1"
        var val = vm._data;
        // {
        //     name: "aa",
        //     age: {
        //         a1: 18
        //     }
        // }

        exp = exp.split('.'); //[age, a1]
        exp.forEach(function(k) {//age
            //val = {
            //         a1: 18
            //     }
            val = val[k];
        });
        return val;
    },
    //设置vm中data里相对应的属性值
    _setVMVal: function(vm, exp, value) {
        var val = vm._data;
        exp = exp.split('.');
        exp.forEach(function(k, i) {
            // 非最后一个key,更新val的值
            if (i < exp.length - 1) {
                val = val[k];
            } else {
                val[k] = value;
            }
        });
    }
};

// a-> b ->c ->d  函数嵌套调用
// a-> a -> a -> 递归 ->特殊的函数嵌套

//更新器 操作原生DOM的方法
var updater = {
    //更新节点的textContent属性
    textUpdater: function(node, value) {
        node.textContent = typeof value == 'undefined' ? '' : value;
    },

    //更新节点的innerHTML属性
    htmlUpdater: function(node, value) {
        node.innerHTML = typeof value == 'undefined' ? '' : value;
    },

    //更新节点的className属性
    classUpdater: function(node, value, oldValue) {
        var className = node.className; //className = > "bb"

        node.className = className + (className?' ':'') + value;  //bb aa


    /*    className = className.replace(oldValue, '').replace(/\s$/, '');

        var space = className && String(value) ? ' ' : '';*/

        // node.className = className + space + value;  //bb aa
    },

    //更新节点的value属性
    modelUpdater: function(node, value, oldValue) {
        node.value = typeof value == 'undefined' ? '' : value;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值