您现在的位置是:网站首页> 编程资料编程资料

vue parseHTML源码解析hars end comment钩子函数_vue.js_

2023-05-24 390人已围观

简介 vue parseHTML源码解析hars end comment钩子函数_vue.js_

引言

接上文  parseHTML 函数源码解析  start钩子函数

接下来我们主要讲解当解析器遇到一个文本节点时会如何为文本节点创建元素描述对象,又会如何对文本节点做哪些特殊的处理。

parseHTML(template, { chars: function(){ //... }, //... }) 

chars源码:

chars: function chars(text) { if (!currentParent) { { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.' ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored.") ); } } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } var children = currentParent.children; text = inPre || text.trim() ? isTextTag(currentParent) ? text : decodeHTMLCached(text) // only preserve whitespace if its not right after a starting tag : preserveWhitespace && children.length ? ' ' : ''; if (text) { var res; if (!inVPre && text !== ' ' && (res = parseText(text, delimiters))) { children.push({ type: 2, expression: res.expression, tokens: res.tokens, text: text }); } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { children.push({ type: 3, text: text }); } } }

当解析器遇到文本节点时,如上代码中的 chars 钩子函数就会被调用,并且接收该文本节点的文本内容作为参数。

我们来看chars钩子函数最开始的这段代码:

if (!currentParent) { { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.' ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored.") ); } } return } 

首先判断了 currentParent 变量是否存在,我们知道 currentParent 变量指向的是当前节点的父节点:。

如果 currentParent 变量不存在说明什么问题?

  • 1:没有根元素,只有文本。
  • 2: 文本在根元素之外。

当遇到第一种情况打印警告信息:"模板必须要有根元素",第二种情况打印警告信息:" 根元素外的文本将会被忽略"。

接下来:

if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } 

这段代码是用来解决 IE 浏览器中渲染