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

你可能感兴趣的文章
OSG学习:纹理映射(六)——灯光
查看>>
OSG学习:纹理映射(四)——三维纹理映射
查看>>
OSG:从源码看Viewer::run() 一
查看>>
osi 负载均衡
查看>>
OSI七层模型与TCP/IP五层模型(转)
查看>>
OSI七层模型与TCP/IP四层与五层模型详解
查看>>
OSI七层模型的TCP/IP模型都有哪几层和他们的对应关系?
查看>>
OSI操作系统(NETBASE第八课)
查看>>
OSM数据如何下载使用(地图数据篇.11)
查看>>
OSPF 四种设备角色:IR、ABR、BR、ASBR
查看>>
OSPF 四种路由类型:Intra Area、Inter Area、第一、二类外部路由
查看>>
OSPF 学习
查看>>
OSPF 支持的网络类型:广播、NBMA、P2MP和P2P类型
查看>>
OSPF 概念型问题
查看>>
OSPF 的主要目的是什么?
查看>>
SQL Server 存储过程分页。
查看>>
OSPF不能发现其他区域路由时,该怎么办?
查看>>
OSPF两个版本:OSPFv3与OSPFv2到底有啥区别?
查看>>
SQL Server 存储过程
查看>>
OSPF在大型网络中的应用:高效路由与可扩展性
查看>>