Vue AST源码解析第一篇

2020-06-13 10:27:46易采站长站整理

下面看接下来的代码:


// 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树的字符串形式,看图就明白了:

下面看最后一段代码:


// 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) {