博客
关于我
实现一个简易Vue(三)Compiler
阅读量:354 次
发布时间:2019-03-04

本文共 1959 字,大约阅读时间需要 6 分钟。

3. Compiler

  • 功能
    • 负责编译模板,解析指令及插值表达式
    • 负责页面的首次渲染
    • 在数据变化后重新渲染视图
  • 代码
class Compiler {     constructor(vm) {       this.el = vm.$el;       this.vm = vm;       this.compile(this.el);     }     compile(el) {       let childNodes = el.childNodes;       Array.from(childNodes).forEach(node => {         if (this.isTextNode(node)) {           this.compileText(node);         } else if (this.isElementNode(node)) {           this.compileElement(node);         }         if (node.childNodes && node.childNodes.length) {           this.compile(node);         }       });     }     compileElement(node) {       Array.from(node.attributes).forEach(attr => {         if (this.isDirective(attr.name)) {           const attrName = attr.name.substring(2);           this.update(node, attr.value, attrName);         }       });     }     update(node, key, attrName) {       const updateFn = this[attrName + 'Updater'];       if (updateFn && updateFn.call(this, node, this.vm[key], key)) {         return true;       }     }     textUpdater(node, value, key) {       node.textContent = value;       new Watcher(this.vm, key, (newValue) => {         node.textContent = newValue;       });     }     modelUpdater(node, value, key) {       node.value = value;       new Watcher(this.vm, key, (newValue) => {         node.value = newValue;       });       node.addEventListener('input', () => {         this.vm[key] = node.value;       });     }     compileText(node) {       const reg = /\{\{(.+?)\}\}/;       const value = node.textContent;       if (reg.test(value)) {         const key = RegExp.$1.trim();         node.textContent = value.replace(reg, this.vm[key]);         new Watcher(this.vm, key, (newValue) => {           node.textContent = newValue;         });       }     }     isDirective(attrName) {       return attrName.startsWith('v-');     }     isTextNode(node) {       return node.nodeType === 3;     }     isElementNode(node) {       return node.nodeType === 1;     } }

转载地址:http://drir.baihongyu.com/

你可能感兴趣的文章
python+flask计算机毕业设计高校物品使用互益平台的设计与实现(程序+开题+论文)
查看>>
Python函数,匿名函数,高阶函数,内置函数——08
查看>>
python+flask计算机毕业设计高校疫情防控管理平台(程序+开题+论文)
查看>>
python+flask计算机毕业设计高校网上迎新系统(程序+开题+论文)
查看>>
python+flask计算机毕业设计高校运动会(程序+开题+论文)
查看>>
python+flask计算机毕业设计高校选课系统(程序+开题+论文)
查看>>
Python+Jenkins+Allure Report接口自动化测试持续集成
查看>>
python+locust电商全流程性能测试
查看>>
Python函数运行的可执行文件的终端输出如何以一般方式静音?
查看>>
Python+Pytest+Allure+Git+Jenkins接口自动化框架
查看>>
python+pytest接口自动化 —— 参数关联
查看>>
python+pytest接口自动化 —— 参数关联
查看>>
Python+pytest接口自动化 —— 接口测试基础
查看>>
python+pytest接口自动化 —— 自动化用例编写思路 (使用pytest编写一个测试脚本)
查看>>
Python+pytest接口自动化之cookie绕过登录(保持登录状态)
查看>>
python+pytest接口自动化:接口测试
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
python+requests+unittest执行自动化接口测试!
查看>>
Python+Requests编码识别Bug
查看>>