Vue编译器源码分析compileToFunctions作用详解

 更新时间:2022年07月13日 17:44:01   作者:李李  
这篇文章主要为大家介绍了Vue编译器源码分析compileToFunctions作用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

引言

接上篇Vue编译器源码分析文章我们来分析:compileToFunctions的作用。

经过前面的讲解,我们已经知道了 compileToFunctions 的真正来源你可能会问为什么要弄的这么复杂?为了搞清楚这个问题,我们还需要继续接触完整的代码。

下面我们继续探索compileToFunctions是如何把模板字符串template编译成渲染函数render的。

Vue.prototype.$mount函数体

回归到Vue.prototype.$mount函数体内。

var ref = compileToFunctions(template, {
	shouldDecodeNewlines: shouldDecodeNewlines,
	shouldDecodeNewlinesForhref: shouldDecodeNewlinesForhref,
	delimiters: options.delimiters,
	comments: options.comments
}, this);

在此传递给compileToFunctions的第一个参数就是模板字符串template,而第二个参数则是一个配置选项options。

先说说这些配置选项中的属性!

shouldDecodeNewlines

源码出处

// check whether current browser encodes a char inside attribute values
var div;
function getShouldDecode(href) {
	div = div || document.createElement('div');
	div.innerHTML = href ? "<a href=\"\n\"/>" : "<div a=\"\n\"/>";
	return div.innerHTML.indexOf('&#10;') > 0
}
// #3663: IE encodes newlines inside attribute values while other browsers don't
var shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false;
// #6828: chrome encodes content in a[href]
var shouldDecodeNewlinesForhref = inBrowser ? getShouldDecode(true) : false;

这个是什么意思呢?

大致的翻译下,在我们innerHTML获取内容时,换行符和制表符分别被转换成了&#10和&#9。在IE中,不仅仅是 a 标签的 href 属性值,任何属性值都存在这个问题。

这就会影响Vue的编译器在对模板进行编译后的结果,为了避免这些问题Vue需要知道什么时候要做兼容工作,如果 shouldDecodeNewlines 为 true,意味着 Vue 在编译模板的时候,要对属性值中的换行符或制表符做兼容处理。而shouldDecodeNewlinesForhref为true 意味着Vue在编译模板的时候,要对a标签的 href 属性值中的换行符或制表符做兼容处理。

options.delimiters & options.comments

两者都是当前Vue实例的$options属性,并且delimiters和comments都是 Vue 提供的选项。

现在我们已经搞清楚了这些配置选项是什么意思,那接下来我们把目光放在《Vue编译器源码分析(二)》针对compileToFunctions函数逐行分析。

compileToFunctions函数逐行分析

function createCompileToFunctionFn(compile) {
	var cache = Object.create(null);
	return function compileToFunctions(
		template,
		options,
		vm
	) {
		options = extend({}, options);
		var warn$$1 = options.warn || warn;
		delete options.warn;
		/* istanbul ignore if */
		{
			// detect possible CSP restriction
			try {
				new Function('return 1');
			} catch (e) {
				if (e.toString().match(/unsafe-eval|CSP/)) {
					warn$$1(
						'It seems you are using the standalone build of Vue.js in an ' +
						'environment with Content Security Policy that prohibits unsafe-eval. ' +
						'The template compiler cannot work in this environment. Consider ' +
						'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
						'templates into render functions.'
					);
				}
			}
		}
		// check cache
		var key = options.delimiters ?
			String(options.delimiters) + template :
			template;
		if (cache[key]) {
			return cache[key]
		}
		// compile
		var compiled = compile(template, options);
		// check compilation errors/tips
		{
			if (compiled.errors && compiled.errors.length) {
				warn$$1(
					"Error compiling template:\n\n" + template + "\n\n" +
					compiled.errors.map(function(e) {
						return ("- " + e);
					}).join('\n') + '\n',
					vm
				);
			}
			if (compiled.tips && compiled.tips.length) {
				compiled.tips.forEach(function(msg) {
					return tip(msg, vm);
				});
			}
		}
		// turn code into functions
		var res = {};
		var fnGenErrors = [];
		res.render = createFunction(compiled.render, fnGenErrors);
		res.staticRenderFns = compiled.staticRenderFns.map(function(code) {
			return createFunction(code, fnGenErrors)
		});
		// check function generation errors.
		// this should only happen if there is a bug in the compiler itself.
		// mostly for codegen development use
		/* istanbul ignore if */
		{
			if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
				warn$$1(
					"Failed to generate render function:\n\n" +
					fnGenErrors.map(function(ref) {
						var err = ref.err;
						var code = ref.code;
						return ((err.toString()) + " in\n\n" + code + "\n");
					}).join('\n'),
					vm
				);
			}
		}
		return (cache[key] = res)
	}
}

注意compileToFunctions函数是接收三个参数的,第三个参数是当前Vue实例。

首先:

options = extend({}, options);
var warn$$1 = options.warn || warn;
delete options.warn;

通过extend 把 options 配置对象上的属性扩展一份到新对象上,定义warn$$1变量。warn是一个错误信息提示的函数。

接下来:

// detect possible CSP restriction
try {
	new Function('return 1');
} catch (e) {
	if (e.toString().match(/unsafe-eval|CSP/)) {
		warn$$1(
			'It seems you are using the standalone build of Vue.js in an ' +
			'environment with Content Security Policy that prohibits unsafe-eval. ' +
			'The template compiler cannot work in this environment. Consider ' +
			'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
			'templates into render functions.'
		);
	}
}

这段代码使用 try catch 语句块对 new Function('return 1') 这句代码进行错误捕获,如果有错误发生且错误的内容中包含如 'unsafe-eval' 或者 'CSP' 这些字样的信息时就会给出一个警告。

CSP全称Content Security Policy ,可以直接翻译为内容安全策略,说白了,就是为了页面内容安全而制定的一系列防护策略. 通过CSP所约束的的规责指定可信的内容来源(这里的内容可以指脚本、图片、iframe、fton、style等等可能的远程的资源)。通过CSP协定,让WEB处于一个安全的运行环境中。

如果你的策略比较严格,那么 new Function() 将会受到影响,从而不能够使用。但是将模板字符串编译成渲染函数又依赖 new Function(),所以解决方案有两个:

  • 1、放宽你的CSP策略
  • 2、预编译

这段代码的作用就是检测 new Function() 是否可用,并在某些极端情况下给你一个有用的提示。

接下来是:

var key = options.delimiters ?
	String(options.delimiters) + template :
	template;
if (cache[key]) {
	return cache[key]
}

options.delimiters这个选项是改变纯文本插入分隔符,如果options.delimiters存在,则使用String 方法将其转换成字符串并与 template 拼接作为 key 的值,否则直接使用 template 字符串作为 key 的值,然后判断 cache[key] 是否存在,如果存在直接返回cache[key]。

这么做的目的是缓存字符串模板的编译结果,防止重复编译,提升性能,我们再看一下compileToFunctions函数的最后一句代码:

return (cache[key] = res)

这句代码在返回编译结果的同时,将结果缓存,这样下一次发现如果 cache 中存在相同的 key则不需要再次编译,直接使用缓存的结果就可以了。

接下来:

// compile
var compiled = compile(template, options);
// check compilation errors/tips
if (compiled.errors && compiled.errors.length) {
	warn$$1(
		"Error compiling template:\n\n" + template + "\n\n" +
		compiled.errors.map(function(e) {
			return ("- " + e);
		}).join('\n') + '\n',
		vm
	);
   }
if (compiled.tips && compiled.tips.length) {
	compiled.tips.forEach(function(msg) {
		return tip(msg, vm);
	});
   }
}

compile 是引用了来自 createCompileToFunctionFn 函数的形参稍后会重点来介绍它。

在使用 compile 函数对模板进行编译后会返回一个结果 compiled,返回结果 compiled 是一个对象且这个对象可能包含两个属性 errors 和 tips 。这两个属性分别包含了编译过程中的错误和提示信息。所以上面那段代码的作用就是用来检查使用 compile 对模板进行编译的过程中是否存在错误和提示的,如果存在那么需要将其打印出来。

接下来:

// turn code into functions
var res = {};
var fnGenErrors = [];
res.render = createFunction(compiled.render, fnGenErrors);
res.staticRenderFns = compiled.staticRenderFns.map(function(code) {
	return createFunction(code, fnGenErrors)
});

res 是一个空对象且它是最终的返回值,fnGenErrors 是一个空数组。

在 res 对象上添加一个 render 属性,这个 render 属性,就是最终生成的渲染函数,它的值是通过 createFunction 创建出来的。

createFunction 函数源码

function createFunction(code, errors) {
	try {
		return new Function(code)
	} catch (err) {
		errors.push({
			err: err,
			code: code
		});
		return noop
	}
}

createFunction 函数接收两个参数,第一个参数 code 为函数体字符串,该字符串将通过new Function(code) 的方式创建为函数。

第二个参数 errors 是一个数组,作用是当采用 new Function(code) 创建函数发生错误时用来收集错误的。

已知,传递给 createFunction 函数的第一个参数是 compiled.render,所以 compiled.render 应该是一个函数体字符串,且我们知道 compiled 是 compile 函数的返回值,这说明:compile函数编译模板字符串后所得到的是字符串形式的函数体。

传递给 createFunction 函数的第二个参数是之前声明的 fnGenErrors 常量,也就是说当创建函数出错时的错误信息被 push 到这个数组里了。

在这句代码之后,又在 res 对象上添加了 staticRenderFns 属性:

res.staticRenderFns = compiled.staticRenderFns.map(function(code) {
	return createFunction(code, fnGenErrors)
});

由这段代码可知 res.staticRenderFns 是一个函数数组,是通过对compiled.staticRenderFns遍历生成的,这说明:compiled 除了包含 render 字符串外,还包含一个字符串数组staticRenderFns ,且这个字符串数组最终也通过 createFunction 转为函数。staticRenderFns 的主要作用是渲染优化,我们后面详细讲解。

最后的代码:

// check function generation errors.
// this should only happen if there is a bug in the compiler itself.
// mostly for codegen development use
/* istanbul ignore if */
if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
	warn$$1(
		"Failed to generate render function:\n\n" +
		fnGenErrors.map(function(ref) {
			var err = ref.err;
			var code = ref.code;
			return ((err.toString()) + " in\n\n" + code + "\n");
		}).join('\n'),
		vm
	);
}
return (cache[key] = res)

这段代码主要的作用是用来打印在生成渲染函数过程中的错误,返回结果的同时将结果缓存,接下来我们讲讲compile 的作用。

Vue编译器源码分析之compile解析

以上就是Vue编译器源码分析compileToFunctions作用详解的详细内容,更多关于Vue编译器compileToFunctions的资料请关注程序员之家其它相关文章!

相关文章

  • 详解基于element的区间选择组件校验(交易金额)

    详解基于element的区间选择组件校验(交易金额)

    这篇文章主要介绍了详解基于element的区间选择组件校验(交易金额),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • vue3页面跳转的两种方式

    vue3页面跳转的两种方式

    vue3的页面跳转有两种方式,第一种是标签内跳转,第二种是编程式路由导航,本文通过实例代码给大家介绍的非常详细,需要的朋友参考下吧
    2023-05-05
  • vue 父组件通过v-model接收子组件的值的代码

    vue 父组件通过v-model接收子组件的值的代码

    这篇文章主要介绍了vue 父组件通过v-model接收子组件的值的代码,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-10-10
  • Vue3配置axios跨域实现过程解析

    Vue3配置axios跨域实现过程解析

    这篇文章主要介绍了Vue3配置axios跨域实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • vue3+ts 依赖注入provide inject的用法

    vue3+ts 依赖注入provide inject的用法

    vue3中引入新的组件传值方式,就是provide/inject依赖注入模式,本文主要介绍了vue3+ts 依赖注入provide inject的用法,感兴趣的可以了解一下
    2023-11-11
  • Vue3实现优雅加载图片的动画效果

    Vue3实现优雅加载图片的动画效果

    这篇文章主要为大家详细介绍了Vue3如何实现加载图片时添加一些动画效果,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以参考下
    2023-10-10
  • Vue实现拖拽式分割布局

    Vue实现拖拽式分割布局

    这篇文章主要为大家详细介绍了Vue实现拖拽式分割布局,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • vue中记录滚动条位置的两种方法

    vue中记录滚动条位置的两种方法

    最近用 Vue 做移动端页面遇到一个问题,需要记住滚动条的位置,所以下面这篇文章主要给大家介绍了关于vue中记录滚动条位置的两种方法,文中给出了详细的实例,需要的朋友可以参考下
    2023-01-01
  • 如何使用JS监听一个变量改变

    如何使用JS监听一个变量改变

    在JS编程中如果能监测变量的内容,当变量值发生变化时,实时发出通知,这定是一项很有用的功能,下面这篇文章主要给大家介绍了关于如何使用JS监听一个变量改变的相关资料,需要的朋友可以参考下
    2023-05-05
  • vue-prop父组件向子组件进行传值的方法

    vue-prop父组件向子组件进行传值的方法

    下面小编就为大家分享一篇vue-prop父组件向子组件进行传值的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-03-03

最新评论

?


http://www.vxiaotou.com