博客
关于我
实现一个简易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/

你可能感兴趣的文章
php在liunx系统中设置777权限不起作用解决方法
查看>>
PHP基于openssl实现的非对称加密操作
查看>>
php基本符号大全
查看>>
php基础篇-二维数组排序 array_multisort
查看>>
php基础配置环境变量
查看>>
php增删改查封装方法
查看>>
springboot之jar包Linux后台启动部署及滚动日志查看且日志输出至文件保存(超级详细)
查看>>
php多条件筛选功能的实现
查看>>
php多线程
查看>>
PHP大数组循环-避免产生Notice或者是Warning
查看>>
PHP大数组过滤元素、修改元素性能分析
查看>>
PHP大文件切片下载代码
查看>>
PHP如何下载远程文件到指定目录
查看>>
php如何优化压缩的图片
查看>>
php如何做表格,新手怎么制作表格
查看>>
RabbitMQ高级特性
查看>>
php如何定义的数位置,php如何实现不借助IDE快速定位行数或者方法定义的文件和位置...
查看>>
RabbitMQ集群 - 普通集群搭建、宕机情况
查看>>
php如何正确的获得文件的后缀名
查看>>
PHP如何生成唯一的数字ID
查看>>