1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| const compileUtil = { getValue(expr, vm){ return expr.split('.').reduce((data,currentVal)=>{ return data[currentVal]; }, vm.$data) }, text(node, expr, vm) { let value; if(expr.indexOf('{{')!==-1){ value = expr.replace(/\{\{(.+?)\}\}/g, (...args)=>{ return this.getValue(args[1], vm); }); }else{ value = this.getValue(expr, vm); } this.updater.textUpdater(node, value); }, html(node, expr, vm) { const value = this.getValue(expr, vm); this.updater.htmlUpdater(node, value); }, model(node, expr, vm) { const value = this.getValue(expr, vm); this.updater.modelUpdater(node, value); }, on(node, expr, vm, detailStr) { let fn = vm.$options.methods && vm.$options.methods[expr]; node.addEventListener(detailStr,fn.bind(vm), false); }, bind(node, expr, vm, detailStr){ node.setAttribute(detailStr, expr); }, updater: { textUpdater(node, value) { node.textContent = value; }, htmlUpdater(node, value){ node.innerHTML = value; }, modelUpdater(node, value){ node.value = value; } }
}
class Compiler { constructor(el, vm) { this.el = this.isElementNode(el) ? el : document.querySelector(el); this.vm = vm; const fragments = this.node2fragments(this.el); this.compile(fragments); this.el.appendChild(fragments); } compile(fragments) { const childNodes = fragments.childNodes; [...childNodes].forEach(child => { if (this.isElementNode(child)) { this.compileElement(child); } else { this.compileText(child); } if(child.childNodes && child.childNodes.length){ this.compile(child); } }) } compileElement(node) { let attributes = node.attributes; [...attributes].forEach(attr => { let {name,value} = attr; if (this.isDirector(name)) { let [, directive] = name.split('-'); let [compileKey, detailStr] = directive.split(':'); compileUtil[compileKey](node, value, this.vm, detailStr); node.removeAttribute('v-' + directive); }else if(this.isEventName(name)){ let [, detailStr] = name.split('@'); compileUtil['on'](node, value, this.vm, detailStr); node.removeAttribute('@' + detailStr); }
})
} compileText(node) { const content = node.textContent; if(/\{\{(.+?)\}\}/.test(content)){ compileUtil['text'](node, content, this.vm); } } isEventName(attrName){ return attrName.startsWith('@'); } isDirector(attrName) { return attrName.startsWith('v-'); } node2fragments(el) { const f = document.createDocumentFragment(); let firstChild; while (firstChild = el.firstChild) { f.appendChild(firstChild); } return f; } isElementNode(node) { return node.nodeType === 1; } }
|