数据驱动
Vue的一个核心思想是数据驱动,即视图是由数据驱动产生的,通过修改数据实现视图的修改,而不是直接操作DOM。相对于传统的前端开发,如使用jQuery库直接操作DOM元素,数据驱动的方式大大简化了代码量,代码逻辑也更为清晰,利于维护。
new Vue
// index.html
<div id="app"></div>
// src/main.js
import Vue from 'vue'
import Router from './router'
import Store from './store'
import App from './App'
new Vue({
el: '#app',
router,
render: h=>h(App),
store
})
上述代码实现了Vue的初始化,那么它实际的初始化过程是怎样的呢?接下去基于Runtime + Compiler模式进行分析。
首先,其入口文件为 src/platforms/web/entry-runtime-with-compiler.js
。在这部分代码中可以看到初始Vue的来源
import Vue from './runtime/index'
打开这个runtime/index.js
文件,可以看到首先从core/index
导入Vue,然后对这个Vue对象进行一系列的扩展。继续打开core/index.js
文件,可以看到从./instance/index
中导入Vue。在instance/index.js
中终于可以看到对Vue的初始定义:
import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'
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)
}
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export default Vue
从上述代码中可以看出,Vue实际上是一个用Function实现的类,且只能通过new Vue
实例化。实例化之后,调用各种...Mixin(Vue)
函数,给Vue的prototype扩展一些方法,最后暴露给全局。用new实例化时,会调用this._init()
方法。这一方法定义在core/instance/init.js
中
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初始化的主要工作包括:合并配置,初始化生命周期,在beforeCreate前初始化事件中心和初始化渲染,在created前初始化data、props、computed、watcher等。初始化完成后,若检测到el
属性,则会调用$mount
方法挂载vm
,将模板渲染成最终的DOM。
实例挂载
通过上述分析,初始化完成后,会调用$mount
方法进行挂载。实际上,不同的平台和构建方式,其挂载方式页不同,所以这个$mount
在多个文件中有不同的定义。web平台的挂载方法定义在src/platform/web/entry-runtime-with-compiler.js
和src/platform/web/runtime/index.js
中,weex平台的则是定义在src/platform/weex/runtime/index.js
。此处针对Runtime + Compiler模式进行分析。
在src/platform/web/entry-runtime-with-compiler.js
中可以看到在Vue原型上的$mount
方法定义如下:
// 缓存原型上的$mount方法
const mount = Vue.prototype.$mount
// 重新定义$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) {
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)
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
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
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
return mount.call(this, el, hydrating)
}
上述代码首先缓存了原型上的$mount
方法,然后对其进行重新定义。首先,限制el
不能是body
或html
,即不能将Vue挂载在这种根节点上。然后判断是否有render
方法,若没有,则会将el
或template
字符串转换成render
方法。最后调用原型上的$mount
方法挂载。
在src/platform/web/runtime/index.js
中可以看到$mount
方法定义如下:
// public mount method
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
方法中传入了两个参数:第一个参数el
表示挂载的元素,可以是字符串或DOM元素,如果是字符串,则在浏览器环境下会调用query
方法将其转换成DOM元素;第二个参数和服务端渲染相关,若是在浏览器环境下不需要传入。$mount
方法的核心是调用mountComponent()
方法,该方法定义在src/core/instance/lifecycle.js
中,其核心代码为
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted) {
callHook(vm, 'beforeUpdate')
}
}
}, true)
hydrating = false
if (vm.$vnode == null) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
在上述代码中,首先实例化一个watcher
,在其回调函数中调用updateComponent
方法,在此方法中会调用vm._render
方法生成虚拟Node,然后调用vm._update
更新DOM。这个过程是一个递归的过程。vm.$vnode
表示Vue实例的父级虚拟Node,所以当其为null
时,表示当前为根Vue实例,此时设置vm._isMounted
为true
,表示实例挂载完毕。
Virtual DOM
Virtual DOM本质上是使用js对象模拟DOM树结构,用VNode描述DOM节点。在src/core/vdom/vnode.js
中,对这个VNode节点进行了如下定义:
export default class VNode {
tag: string | void;
data: VNodeData | void;
children: ?Array<VNode>;
text: string | void;
elm: Node | void;
ns: string | void;
context: Component | void; // rendered in this component's scope
key: string | number | void;
componentOptions: VNodeComponentOptions | void;
componentInstance: Component | void; // component instance
parent: VNode | void; // component placeholder node
// strictly internal
raw: boolean; // contains raw HTML? (server only)
isStatic: boolean; // hoisted static node
isRootInsert: boolean; // necessary for enter transition check
isComment: boolean; // empty comment placeholder?
isCloned: boolean; // is a cloned node?
isOnce: boolean; // is a v-once node?
asyncFactory: Function | void; // async component factory function
asyncMeta: Object | void;
isAsyncPlaceholder: boolean;
ssrContext: Object | void;
fnContext: Component | void; // real context vm for functional nodes
fnOptions: ?ComponentOptions; // for SSR caching
devtoolsMeta: ?Object; // used to store functional render context for devtools
fnScopeId: ?string; // functional scope id support
constructor (
tag?: string,
data?: VNodeData,
children?: ?Array<VNode>,
text?: string,
elm?: Node,
context?: Component,
componentOptions?: VNodeComponentOptions,
asyncFactory?: Function
) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
this.ns = undefined
this.context = context
this.fnContext = undefined
this.fnOptions = undefined
this.fnScopeId = undefined
this.key = data && data.key
this.componentOptions = componentOptions
this.componentInstance = undefined
this.parent = undefined
this.raw = false
this.isStatic = false
this.isRootInsert = true
this.isComment = false
this.isCloned = false
this.isOnce = false
this.asyncFactory = asyncFactory
this.asyncMeta = undefined
this.isAsyncPlaceholder = false
}
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
get child (): Component | void {
return this.componentInstance
}
}
从上述代码中可看出,VNode其实是对真实DOM的一种抽象描述,包含了许多节点的属性,如标签名、数据、子节点、父节点、键值等。VNode只是用来映射到真实DOM的渲染,不包含操作DOM的具体方法。在映射到真实DOM的过程中,会经历create、diff、patch等过程。
未完待续。。。