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
| class Vue { constructor(options) { if (typeof options.beforeCreate === 'function') { options.beforeCreate.bind(this)() } this.$data = options.data + this.proxyData() + this.observe() + this.$watchEvent = {} this.$methods = options.methods if (typeof options.created === 'function') { options.created.bind(this)() } if (typeof options.beforeMount === 'function') { options.beforeMount.bind(this)() } this.$el = document.querySelector(options.el) this.compile(this.$el) if (typeof options.mounted === 'function') { options.mounted.bind(this)() } } compile(node) { node.childNodes.forEach(e => { if (e.nodeType === 1) { ... } if (e.nodeType === 3) { const reg = /\{\{(.*?)\}\}/g const text = e.textContent e.textContent = text.replace(reg, (match, vmKey) => { vmKey = vmKey.trim() + if(this.hasOwnProperty(vmKey)) { + let watcher = new Watcher(this, vmKey, e, 'textContent') + if(this.$watchEvent[vmKey]){ + this.$watchEvent[vmKey].push(watcher) + }else{ + this.$watchEvent[vmKey] = [] + this.$watchEvent[vmKey].push(watcher) + } + } return this.$data[vmKey] }) } }); } + proxyData() { + for (const key in this.$data) { + Object.defineProperty(this, key, { + get() { + return this.$data[key] + }, + set(val){ + this.$data[key] = val + } + }) + } + } + observe(){ + for (const key in this.$data) { + let value = this.$data[key] + const _this = this + Object.defineProperty(this.$data, key, { + get(){ + return value + }, + set(val){ + value = val + if(_this.$watchEvent[key]){ + + _this.$watchEvent[key].forEach((item, index) => { + item.update() + }) + } + } + }) + } + } +}
+ class Watcher { + constructor(vm, key, node, attr){ + this.vm = vm + this.key = key + this.node = node + this.attr = attr + } + + update(){ + this.node[this.attr] = this.vm[this.key] + } + }
|