源码学习七 —— template 解析过程学习"/>
vue 模板解析成html,Vue.js 源码学习七 —— template 解析过程学习
这次,来学习下Vue是如何解析HTML代码的。
template 解析用在哪
从之前学习 Render 的过程中我们知道,template 的编译在 $mount 方法中出现过。
// src/platforms/web/entry-runtime-with-compiler.js
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
return this
}
const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
// 首字母为#号,看作是ID。
template = idToTemplate(template)
}
} else if (template.nodeType) {
// 为真实 DOM,直接获取html
template = template.innerHTML
} else {
return this
}
} else if (el) {
// 获取 HTML
template = getOuterHTML(el)
}
if (template) {
// 进行编译并赋值给 vm.$options
const { render, staticRenderFns } = compileToFunctions(template, {
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: optionsments
}, this)
// 渲染函数
options.render = render
// 静态渲染方法
options.staticRenderFns = staticRenderFns
}
}
return mount.call(this, el, hydrating)
}
其实以上代码总结起来就4步:
获取el元素。
判断el是否为body或者html。
为$options编译render函数。
执行之前的mount函数。
关键在于第三步,编译 render 函数上。先获取 template,即获取HTML内容,然后执行 compileToFunctions 来编译,最后将 render 和 staticRenderFns 传给 vm.$options 对象。
顺便看看这两个方法都用在哪里?
// src/core/instance/render.js
Vue.prototype._render = function (): VNode {
try {
vnode = render.call(vm._renderProxy, vm.$createElement)
} catch (e) {
handleError(e, vm, `render`)
}
return vnode
<更多推荐
vue 模板解析成html,Vue.js 源码学习七 —— template 解析过程学习
发布评论