JS實現一個v-if

李文楊發表於2018-07-16
// 獲取dom
var el = document.getElementById('root');

        console.log(el);
// 遍歷dom
        function dealNode(el) {
            var childNodes = el.childNodes;
            [].slice.call(childNodes).forEach((node)=>{
                if(node.nodeType == 1){
                    //節點元素的屬性
                    var nodeAttrs = node.attributes;
                    console.log(nodeAttrs);
                    [].slice.call(nodeAttrs).forEach((attr) => {
                        var attrName = attr.name;
                        if(isDeretive(attrName)){
                            var exp = attr.value;
                            var dir = attr.name.substring(2);
                            console.log('指令型別',dir);
                            console.log('指令的值',exp);
                            if(dir == 'if' && (exp=='false')){
                                node.parentNode.removeChild(node);
                            }
                        }
                    });
                }
        
                //節點深層遍歷
                if(node.childNodes && node.childNodes.length){
                    dealNode(node);
                }
            })
        }
        dealNode(el);
        
        function isDeretive(attr) {
            return attr.indexOf('r-') == 0;
        }

 

相關文章