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: options.comments

}, 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

<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值