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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
|
var Vue = (function() { function Vue(options) { this.$el = document.querySelector(options.el); this.$data = options.data(); this._init(this, options.template, options.methods); } Vue.prototype._init = function(vm, template, methods) {
var container = document.createElement('div'); container.innerHTML = template;
var showPool = new Map(); var eventPool = new Map(); initData(vm, showPool); initPool(container, methods, showPool, eventPool); bindEvent(vm, eventPool); render(vm, showPool, container); }
function initData(vm, showPool) { var _data = vm.$data;
for (var key in _data) { (function(key) { Object.defineProperty(vm, key, { get: function() { return _data[key]; }, set: function(newVal) { _data[key] = newVal; update(vm, key, showPool) } }); })(key); } }
function initPool(container, methods, showPool, eventPool) { var _allNodes = container.getElementsByTagName('*'); var dom = null; for (var i = 0; i < _allNodes.length; i++) { dom = _allNodes[i]; var vIfData = dom.getAttribute('v-if'); var vShowData = dom.getAttribute('v-show'); var vEvent = dom.getAttribute('@click');
if (vIfData) { showPool.set( dom, { type: 'if', prop: vIfData } ) dom.removeAttribute('v-if'); } else if (vShowData) { showPool.set( dom, { type: 'show', prop: vShowData } ) dom.removeAttribute('v-show'); }
if (vEvent) { eventPool.set( dom, methods[vEvent] ) dom.removeAttribute('@click'); } } console.log(eventPool); }
function bindEvent(vm, eventPool) { for (var [dom, handler] of eventPool) { vm[handler.name] = handler; dom.addEventListener('click', vm[handler.name].bind(vm), false); } }
function render(vm, showPool, container) { var _data = vm.$data; var _el = vm.$el;
for (var [dom, info] of showPool) { switch (info.type) { case 'if': info.comment = document.createComment('v-if'); !_data[info.prop] && dom.parentNode.replaceChild(info.comment, dom); break; case 'show': !_data[info.prop] && (dom.style.display = 'none'); break; default: break; } }
_el.appendChild(container); }
function update(vm, key, showPool) { var _data = vm.$data;
for (var [dom, info] of showPool) { if (info.prop === key) { switch (info.type) { case 'if': !_data[key] ? dom.parentNode.replaceChild(info.comment, dom) : info.comment.parentNode.replaceChild(dom, info.comment); break; case 'show': !_data[key] ? (dom.style.display = 'none') : (dom.removeAttribute('style')); break; default: break; } } } }
return Vue; })(); export default Vue;
|