装作无所畏惧的样子,之后会越来越勇敢
vue的核心思想是数据驱动。所谓数据驱动,就是指视图是由数据驱动生成的,想要对视图进行修改,不会直接操作DOM,而是通过修改数据。这样,我们在开发时候只需要关注数据的修改,DOM变成了数据的映射。
接下来让我们看看vue是如何实现的。接下来我们先弄清楚模板和数据是如何渲染成最终的DOM。
来看源码,在/vue/src/core/index.js中
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
接下来我们看_init做了什么
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// a uid
vm._uid = uid++
let startTag, endTag
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`
endTag = `vue-perf-end:${vm._uid}`
mark(startTag)
}
// a flag to avoid this being observed
vm._isVue = true
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false)
mark(endTag)
measure(`vue ${vm._name} init`, startTag, endTag)
}
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
Vue初始化主要干了几件事,合并配置、初始化生命周期、初始化事件中心、初始化渲染、初始化data、props、computed、watch等等。
我们目前的主要目的是弄清楚模板和数据如何渲染成最终的DOM。所以我们需要关注:
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
如果有el属性,则调用vm.$mount方法挂载vm,挂载的目标是把模板渲染到最终的DOM。继续追踪vm.$mount
$mount在src/platform/web/entry-runtime-with-compiler.js、src/platform/web/runtime/index.js、src/platform/weex/runtime/index.js这几个文件都有定义,,因为$mount的实现是和平台和构建方式都相关的。我么重点看compiler版本的$mount的实现。
// 缓存了原型上的$mount
const mount = Vue.prototype.$mount
// 重新定义该方法
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
/* istanbul ignore if */
// 对el进行了限制,vue不能挂在在body、html节点上
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
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) === '#') {
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 {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
template = getOuterHTML(el)
}
// 以上拿到template
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
// 解构赋值,获得render和staticRenderFns的值
const { render, staticRenderFns } = compileToFunctions(template, {
outputSourceRange: process.env.NODE_ENV !== 'production',
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
// 将上面获取的render和staticRenderFns方法赋值给options的方法
options.render = render
options.staticRenderFns = staticRenderFns
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
// 最后调用原型上的mount方法挂载
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
上面其实重点做了一件事,就是如果没有render方法,则会把el或者template字符串转换成render方法。无论是用单文件.vue方法开发组件,还是写了el或者template属性,都会转换成render方法。这个过程是个Vue的在线编译的过程,它是调用compileToFunctions方法实现的。
mount方法,在src/platform/web/runtime/index.js中定义:
// public mount method
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
mount方法传入两个参数,el和hydrating,el必须是字符串或者DOM对象,如果是字符串在浏览器环境会调用query方法转换成DOM对象。第二个参数是和服务器渲染相关,在浏览器环境不需要传。mountComponent方法,在core/instance/lifecycle中定义:
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
)
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
callHook(vm, 'beforeMount')
// 定义updateComponent方法:vm._update(vnode,hydrating);
let updateComponent
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
updateComponent = () => {
const name = vm._name
const id = vm._uid
const startTag = `vue-perf-start:${id}`
const endTag = `vue-perf-end:${id}`
mark(startTag)
// 生成虚拟Node
const vnode = vm._render()
mark(endTag)
measure(`vue ${name} render`, startTag, endTag)
mark(startTag)
// 更新DOM
vm._update(vnode, hydrating)
mark(endTag)
measure(`vue ${name} patch`, startTag, endTag)
}
} else {
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
}
// we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
// 把vm ,updateComponent ...作为参数传进new Watcher;
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
hydrating = false
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
//判断为根节点的时候设置vm._isMounted 为true,表示这个实例已经挂载,同时执行mounted钩子函数。
// vm.$vnode 表示Vue实例的父虚拟Node,所以则表示当前是根Vue的实例
if (vm.$vnode == null) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}
countComponent 核心是先实例化一个渲染Watcher,在他的回调函数中会调用updatComponent方法,核心:vm._update(vm._render(), hydrating)在此方法先生成虚拟DOM,最终调用vm.updata更新DOM;
mountComponent完成了整个渲染过程,其中最核心的方法是vm._render和 vm._update。
愿我们有能力不向生活缴械投降---Lin