博客
关于我
实现一个简易Vue(三)Compiler
阅读量:353 次
发布时间: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/

你可能感兴趣的文章
SpringBoot处理JSON数据
查看>>
Redis使用基本套路
查看>>
php 解决项目中多个自动加载冲突问题
查看>>
PHP 设置调试工具XDebug PHPStorm IDE
查看>>
php 身份证号检测
查看>>
PHP 输入输出流合集
查看>>
PHP 过滤器(Filter)
查看>>
php 运算符and or && || 的详解
查看>>
php 返回html字符串长度限制,记一次js中和php中的字符串长度计算截取的终极问题和完美...
查看>>
php 阿里云oss 上传回调
查看>>
PHP 面向对象 final类与final方法
查看>>
php+JQ+EasyUI自动加载数据
查看>>
php+sql server根据自增序号id区间查询第几条到第几条的数据
查看>>
php--------获取当前时间、时间戳
查看>>
Redis使用场景举例
查看>>
php--正则表达式
查看>>
php--防止sql注入的方法
查看>>
PHP-CGI Windows平台远程代码执行漏洞复现(CVE-2024-4577)
查看>>
php-cgi耗尽报502错误
查看>>
php-cgi(fpm-cgi) 进程 CPU 100% 与 file_get_content...
查看>>