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

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

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 => {    // Array.from() 将伪数组转化为数组      // 处理文本节点      if (this.isTextNode(node)) {           this.compileText(node)      } else if (this.isElementNode(node)) {           // 处理元素节点        this.compileElement(node)      }      // 判断node节点,是否有子节点,如果有子节点,要递归调用compile      if (node.childNodes && node.childNodes.length) {           this.compile(node)      }    })  }  // 编译元素节点,处理指令  compileElement(node) {       // console.log(node.attributes)    // 遍历所有的属性节点    Array.from(node.attributes).forEach(attr => {         // 判断是否是指令      let attrName = attr.name      if (this.isDirective(attrName)) {           // v-text --> text        attrName = attrName.substr(2)        let key = attr.value        this.update(node, key, attrName)      }    })  }  update(node, key, attrName) {       let updateFn = this[attrName + 'Updater']    updateFn && updateFn.call(this, node, this.vm[key], key)  }  // 处理 v-text 指令  textUpdater(node, value, key) {       node.textContent = value    new Watcher(this.vm, key, (newValue) => {         node.textContent = newValue    })  }  // v-model  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) {       // console.dir(node)    // {   {  msg }}    let reg = /\{\{(.+?)\}\}/    let value = node.textContent    if (reg.test(value)) {         let key = RegExp.$1.trim()      node.textContent = value.replace(reg, this.vm[key])      // 创建watcher对象,当数据改变更新视图      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/

你可能感兴趣的文章
重读&笔记系列-《Linux多线程服务端编程》第一章
查看>>
解决ubuntu在虚拟机(VMware)环境下不能联网的问题
查看>>
LeetCode - 字符串相乘
查看>>
Python raw_input输入 与字符串 在网址编码的不同
查看>>
maya里创建不同颜色大小的HeadsUpDisplay的效果
查看>>
windows使用AutoHotkey工具切换用户
查看>>
python 导航栏
查看>>
Python根据程序名称结束进程
查看>>
C# 适配器模式
查看>>
二分查找与插入排序的结合使用
查看>>
71 简化路径(模拟、栈)
查看>>
892 三维形体的表面积(分析)
查看>>
40. 组合总和 II(dfs、set去重)
查看>>
16 最接近的三数之和(排序、双指针)
查看>>
1333 餐厅过滤器(treemap映射)
查看>>
python中的all函数
查看>>
1137 第 N 个泰波那契数(迭代、记忆性递归)
查看>>
279 完全平方数(dfs)
查看>>
279 完全平方数(bfs)
查看>>
865 具有所有最深结点的最小子树(递归)
查看>>