vue 模板解析成html,Vue.js 源码学习七 —— template 解析过程学习

编程入门 行业动态 更新时间:2024-10-27 20:35:23

vue 模板解析成html,Vue.js <a href=https://www.elefans.com/category/jswz/34/1770099.html style=源码学习七 —— 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 解析过程学习

本文发布于:2024-03-14 06:57:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1735893.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:源码   模板   过程   html   vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!