Vue的编译渲染过程
template => ast => render函数 => VDOM => 真实DOM
runtime-with-compiler
new Vue({
el:'#app',
components:{APP},
remplate:'<APP/>'
})
渲染成最终真实DOM的过程 template ==> ast ==> render ==> vdom ==> UI
new Vue({
el:'#app',
render: h=>h(APP)
})
渲染成最终真实DOM的过程 render ==> vdom ==> UI
render ==> vdom ==> UI
runtime-compiler | runtime-only |
---|---|
体积更大(有compiler代码) | 体积更小 |
有Vue.compilerAPI | 无Vue.compilerAPI |
可以使用template模板、render函数渲染 | 只能使用render函数渲染 |
那么造成这两个区别的到底是什么呢?
原因在于
runtime-with-compiler的打包入口文件是src/platforms/web/entry-runtime-with-compiler.js
runtime-only的打包入口文件是src/platforms/web/entry-runtime.js
runtime-with-compiler实际上引用的就是runtime-only,他们两个唯一的区别就是src/platforms/web/entry-runtime-with-compiler.js,如下我已将不重要的一些代码删除掉了,来看一下:
import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'
import Vue from './runtime/index'
import { query } from './util/index'
import { compileToFunctions } from './compiler/index'
import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'
const idToTemplate = cached(id => {
const el = query(id)
return el && el.innerHTML
})
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
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) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
const { render, staticRenderFns } = compileToFunctions(template, {
outputSourceRange: process.env.NODE_ENV !== 'production',
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
}
}
return mount.call(this, el, hydrating)
}
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el: Element): string {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div')
container.appendChild(el.cloneNode(true))
return container.innerHTML
}
}
Vue.compile = compileToFunctions
export default Vue
以上代码就是对runtime-only的代码进行包装(改写了Vue.prototype.$mount方法)。如果没有render函数,就利用template转成render函数。即下图中红色背景的过程:
template => ast => render函数 => VDOM => 真实DOM
so,以上就是runtime-onley和runtime-with-compiler的区别就清楚了!如有哪里理解错误以及书写错误,欢迎留言指正!