浅析vue中的MVVM实现原理(2)

class Compile { constructor(el, vm) { this.el = this.isElementNode(el) ? el : document.querySelector(el); this.vm = vm; if (this.el) { let fragment = this.node2frament(this.el); this.compile(fragment); this.el.appendChild(fragment) } } //辅助方法 isElementNode(node) { return node.nodeType === 1; } isDirective(name) { return name.includes('v-') } //核心方法 compileElement(node) { let attrs = node.attributes; Array.from(attrs).forEach(attr => { let attrName = attr.name; if (this.isDirective(attrName)) { let expr = attr.value; let [, type] = attrName.split('-'); CompileUtil[type](node, this.vm, expr) } }) } compileText(node) { console.log(node) let expr = node.textContent; let reg = /\{\{([^}]+)\}\}/g; if (reg.test(expr)) { CompileUtil['text'](node, this.vm, expr) } } compile(fragment) { let childNodes = fragment.childNodes; Array.from(childNodes).forEach(node => { if (this.isElementNode(node)) { this.compileElement(node) this.compile(node) } else { this.compileText(node) } }) } node2frament(el) { let fragment = document.createDocumentFragment(); let firstChild; while (firstChild = el.firstChild) { fragment.appendChild(firstChild); } return fragment } } CompileUtil = { getVal(vm, expr) { // 获取实例上对应的数据 expr = expr.split('.'); // [message,a] return expr.reduce((prev, next) => { // vm.$data.a return prev[next]; }, vm.$data); }, getTextVal(vm, expr) { // 获取编译文本后的结果 return expr.replace(/\{\{([^}]+)\}\}/g, (...arguments) => { return this.getVal(vm, arguments[1]); }) }, text(node, vm, expr) { //文本处理 let updateFn = this.updater['textUpdater']; let value = this.getTextVal(vm, expr); updateFn && updateFn(node, value) }, model(node, vm, expr) { let updateFn = this.updater['modelUpdater']; updateFn && updateFn(node, this.getVal(vm, expr)); }, updater: { textUpdater(node, value) { node.textContent = value; }, modelUpdater(node, value) { node.value = value; } } }

v-model类型

modelUpdater(node, value) { node.value = value; console.log(node) console.log(value) console.log(node.value) }

浅析vue中的MVVM实现原理

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/bc57c64d20442fe776d2cecc57ed1d71.html