
实现一个简易Vue(三)Compiler
发布日期:2021-05-07 18:33:29
浏览次数:7
分类:技术文章
本文共 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 }}
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月10日 20时31分09秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
随机四则运算
2019-03-04
Java面向对象
2019-03-04
JAVA带标签的break和continue
2019-03-04
Java获取线程基本信息的方法
2019-03-04
Java集合Collection
2019-03-04
SpringBoot快速入门
2019-03-04
医疗管理系统-手机快速登录和SpringSecurity权限控制
2019-03-04
vue源码分析(MVVM篇)
2019-03-04
React(八)- ReactUI组件库及Redux的使用
2019-03-04
TypeScript系列文章导航
2019-03-04
hibernate和mybatis的区别
2019-03-04
Java中Map的用法详解
2019-03-04
base64编码字符串和图片的互转
2019-03-04
汉字转为拼音
2019-03-04
linux 下安装kolla报错 提示Cannot uninstall requests
2019-03-04
设计模式之组合模式
2019-03-04
(恋上数据结构笔记):优先级队列(Priority Queue)
2019-03-04
(Python学习笔记):字典
2019-03-04