Vue AST源码解析第一篇


Posted in Javascript onJuly 19, 2017

讲完了数据劫持原理和一堆初始化,现在是DOM相关的代码了。

上一节是从这个函数开始的:

// Line-3924
 Vue.prototype._init = function(options) {
  // 大量初始化
  // ...
  // Go!
  if (vm.$options.el) {
   vm.$mount(vm.$options.el);
  }
 };

弄完data属性的数据绑定后,开始处理el属性,也就是挂载的DOM节点,这里的vm.$options.el也就是传进去的'#app'字符串。

有一个值得注意的点是,源码中有2个$mount函数都是Vue$3的原型函数,其中一个标记了注释public mount method,在7531行,另外一个在9553行。打断点进入的是后面,因为定义的晚,覆盖了前面的函数。

// Line-7531
 // public mount method
 Vue$3.prototype.$mount = function(el,hydrating) {
  el = el && inBrowser ? query(el) : undefined;
  return mountComponent(this, el, hydrating)
 };

 // Line-9552
 var mount = Vue$3.prototype.$mount;
 Vue$3.prototype.$mount = function(
  el,
  hydrating
 ) {
  // ...很多代码
  return mount.call(this, el, hydrating)
 };

现在进入后面的$mount函数看看内部结构:

// Line-9552
 var mount = Vue$3.prototype.$mount;
 Vue$3.prototype.$mount = function(el,hydrating) {
  // 将el格式化为DOM节点
  el = el && query(el);
  // 判断是否挂载到body或者html标签上
  if (el === document.body || el === document.documentElement) {
   "development" !== 'production' && warn(
    "Do not mount Vue to <html> or <body> - mount to normal elements instead."
   );
   return this
  }

  var options = this.$options;
  // 处理template/el 转换为渲染函数
  if (!options.render) {
   // ...非常多代码
  }
  return mount.call(this, el, hydrating)
 };

代码前半段首先将el转换为DOM节点,并判断是否挂载到body或者html标签,看看简单的query函数:

// Line-4583
 function query(el) {
  // 如果是字符串就调用querySelector
  if (typeof el === 'string') {
   var selected = document.querySelector(el);
   if (!selected) {
    "development" !== 'production' && warn(
     'Cannot find element: ' + el
    );
    // 找不到就返回一个div
    return document.createElement('div')
   }
   return selected
  }
  // 不是字符串就默认传进来的是DOM节点 
  else {
   return el
  }
 }

函数比较简单,值得注意的几个点是,由于调用的是querySelector方法,所以可以传标签名、类名、C3新选择器等,都会返回查询到的第一个。当然,总是传一个ID或者确定的DOM节点才是正确用法。

下面看接下来的代码:

// Line-9552
 var mount = Vue$3.prototype.$mount;
 Vue$3.prototype.$mount = function(el,hydrating) {
  // ...el转换为DOM节点
  // ...
  // 没有render属性 进入代码段
  if (!options.render) {
   var template = options.template;
   // 没有template 跳
   if (template) {
    if (typeof template === 'string') {
     if (template.charAt(0) === '#') {
      template = idToTemplate(template);
      /* istanbul ignore if */
      if ("development" !== 'production' && !template) {
       warn(
        ("Template element not found or is empty: " + (options.template)),
        this
       );
      }
     }
    } else if (template.nodeType) {
     template = template.innerHTML;
    } else {
     {
      warn('invalid template option:' + template, this);
     }
     return this
    }
   }
   // 有el 获取字符串化的DOM树
   else if (el) {
    template = getOuterHTML(el);
   }
   if (template) {
    // ...小段代码
   }
  }
  return mount.call(this, el, hydrating)
 };

由于没有template属性,会直接进入第二个判断条件,调用getOuterHTML来初始化template变量,函数比较简单, 来看看:

// Line-9623
 function getOuterHTML(el) {
  if (el.outerHTML) {
   return el.outerHTML
  }
  // 兼容IE中的SVG
  else {
   var container = document.createElement('div');
   container.appendChild(el.cloneNode(true));
   return container.innerHTML
  }
 }

简单来讲,就是调用outerHTML返回DOM树的字符串形式,看图就明白了:

Vue AST源码解析第一篇

下面看最后一段代码:

// Line-9552
 var mount = Vue$3.prototype.$mount;
 Vue$3.prototype.$mount = function(el,hydrating) {
  // ...el转换为DOM节点
  // ...
  // 没有render属性 进入代码段
  if (!options.render) {
   // ...处理template
   // ...
   if (template) {
    // 编译开始
    if ("development" !== 'production' && config.performance && mark) {
     mark('compile');
    }

    // 将DOM树字符串编译为函数
    var ref = compileToFunctions(template, {
     shouldDecodeNewlines: shouldDecodeNewlines,
     delimiters: options.delimiters
    }, this);
    // options添加属性
    var render = ref.render;
    var staticRenderFns = ref.staticRenderFns;
    options.render = render;
    options.staticRenderFns = staticRenderFns;

    // 编译结束
    if ("development" !== 'production' && config.performance && mark) {
     mark('compile end');
     measure(((this._name) + " compile"), 'compile', 'compile end');
    }
   }
  }
  return mount.call(this, el, hydrating)
 };

忽略2段dev模式下的提示代码,剩下的代码做了3件事,调用compileToFunctions函数肢解DOM树字符串,将返回的对象属性添加到options上,再次调用mount函数。

首先看一下compileToFunctions函数,该函数接受3个参数,分别为字符串、配置对象、当前vue实例。

由于函数比较长,而且部分是错误判断,简化后如下:

// Line-9326
 function compileToFunctions(template,options,vm) {
  // 获取配置参数
  options = options || {};

  // ...

  var key = options.delimiters ?
   String(options.delimiters) + template :
   template;
  // 检测缓存
  if (functionCompileCache[key]) {
   return functionCompileCache[key]
  }

  // 1
  var compiled = compile(template, options);

  // ...

  // 2
  var res = {};
  var fnGenErrors = [];
  res.render = makeFunction(compiled.render, fnGenErrors);
  var l = compiled.staticRenderFns.length;
  res.staticRenderFns = new Array(l);
  for (var i = 0; i < l; i++) {
   res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i], fnGenErrors);
  }

  // ...

  // 3
  return (functionCompileCache[key] = res)
 }

可以看到,这个函数流程可以分为4步,获取参数 => 调用compile函数进行编译 => 将得到的compiled转换为函数 => 返回并缓存。

 第一节现在这样吧。一张图总结下:

Vue AST源码解析第一篇

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
各浏览器中querySelector和querySelectorAll的实现差异分析
May 23 Javascript
JavaScript判断表单提交时哪个radio按钮被选中的方法
Mar 21 Javascript
jQuery实现打开页面渐现效果示例
Jul 27 Javascript
AngularJs Understanding the Controller Component
Sep 02 Javascript
详解vue项目首页加载速度优化
Oct 18 Javascript
浅谈Vue的加载顺序探讨
Oct 25 Javascript
jQuery图片加载失败替换默认图片方法汇总
Nov 29 jQuery
微信小程序block的使用教程
Apr 01 Javascript
Angular5中状态管理的实现
Sep 03 Javascript
JS判断数组里是否有重复元素的方法小结
May 21 Javascript
jQuery实现高度灵活的表单验证功能示例【无UI】
Apr 30 jQuery
UEditor 自定义图片视频尺寸校验功能的实现代码
Oct 20 Javascript
Vue之Watcher源码解析(1)
Jul 19 #Javascript
angular.js + require.js构建模块化单页面应用的方法步骤
Jul 19 #Javascript
Vue学习笔记进阶篇之多元素及多组件过渡
Jul 19 #Javascript
vue中的非父子间的通讯问题简单的实例代码
Jul 19 #Javascript
Vue之Watcher源码解析(2)
Jul 19 #Javascript
Angular.js项目中使用gulp实现自动化构建以及压缩打包详解
Jul 19 #Javascript
JS+canvas实现的五子棋游戏【人机大战版】
Jul 19 #Javascript
You might like
回答PHPCHINA上的几个问题:URL映射
2007/02/14 PHP
PHP删除数组中的特定元素的代码
2012/06/28 PHP
PHP中的函数-- foreach()的用法详解
2013/06/24 PHP
PHP常用数组函数介绍
2014/07/28 PHP
PHP htmlspecialchars()函数用法与实例讲解
2019/03/08 PHP
JavaScript入门教程 Cookies
2009/01/31 Javascript
jQuery对象与DOM对象之间的转换方法
2010/04/15 Javascript
重载toString实现JS HashMap分析
2011/03/13 Javascript
JavaScript基础语法之js表达式
2016/06/07 Javascript
JSON获取属性值方法代码实例
2020/06/30 Javascript
vue中使用router全局守卫实现页面拦截的示例
2020/10/23 Javascript
[01:00:52]2018DOTA2亚洲邀请赛 4.4 淘汰赛 EG vs LGD 第一场
2018/04/05 DOTA
10种检测Python程序运行时间、CPU和内存占用的方法
2015/04/01 Python
Python解析nginx日志文件
2015/05/11 Python
python学习数据结构实例代码
2015/05/11 Python
Python的消息队列包SnakeMQ使用初探
2016/06/29 Python
Linux下为不同版本python安装第三方库
2016/08/31 Python
简单了解什么是神经网络
2017/12/23 Python
解决python 输出是省略号的问题
2018/04/19 Python
Window环境下Scrapy开发环境搭建
2018/11/18 Python
Python八皇后问题解答过程详解
2019/07/29 Python
python3通过qq邮箱发送邮件以及附件
2020/05/20 Python
澳大利亚和新西兰最大的在线旅行社之一:Aunt Betty
2019/08/07 全球购物
会计专业毕业生自我评价
2013/09/25 职场文书
巡警年度自我鉴定
2014/02/21 职场文书
各营销点岗位职责范本
2014/03/05 职场文书
家长会演讲稿
2014/04/26 职场文书
多媒体教室标语
2014/06/26 职场文书
学习“七一”讲话精神体会
2014/07/08 职场文书
学生安全责任书模板
2014/07/25 职场文书
党课培训心得体会
2014/09/02 职场文书
中秋节国旗下演讲稿
2014/09/13 职场文书
政工师工作总结2015
2015/05/26 职场文书
2016年七夕情人节宣传语
2015/11/25 职场文书
win10下go mod配置方式
2021/04/25 Golang
剑指Offer之Java算法习题精讲二叉树专项训练
2022/03/21 Java/Android