Vue框架的一个核心理念就是数据驱动视图。何谓数据驱动视图?简单理解,就是在我们想改变浏览器视图的时候,仅仅通过修改数据就可以完成。这个过程,大大简化了传统的前端开发的代码量,从而开发过程中不用考虑DOM的修改,不需考虑复杂的DOM操作,只需要将逻辑重点关注在数据的改变即可。
那这是怎么实现的呢?其实主要可以分为两个场景来分析:
比如如下代码:
<div id="app">
{{ message }}
</div>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
这些看似非常简单的代码是如何渲染到浏览器的页面上面的呢?
<div id="app">
{{ message }}
</div>
<button @click="handleClick"></button>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
methods: {
handleClick() {
this.message = 'Hello huihui_new'
}
}
})
又比如说我们点击按钮改变了message的值,页面上立马更新了,这个过程又是如何发生的?
这两个过程如果清楚了,对vue的理解肯定会更深刻。
那么该如何分析这两个过程,那就开始读源码吧!
发生了什么?接下来我们以1.1中的代码来进行分析,new Vue(options)的时候到底发生了什么。
在src/core/instance的目录下,有下面一段代码:
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构造函数,所以在外部我们必须使用new 的方法去实例化Vue,实例化Vue的过程中执行了_init(options)方法(options是我们实例化的时候传入的配置对象)。
init()方法是在initMixin(Vue)的过程中挂载到vue上面的,
export function initMixin(Vue: Class<Component>) {
// 挂载到vue上
Vue.prototype._init = function (options?: Object) {
// vm是Vue
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 {
// Vue._renderProxy指向自身
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);
}
// options对象里面有el 这里的el:'#app',
if (vm.$options.el) {
// 执行Vue.$mount('#app') 挂载
vm.$mount(vm.$options.el);
}
};
}
这个过程中 主要做了几件事:
那data是如何渲染到页面呢,我们继续看源码,在上面第二步中执行了initState(vm),初始化了传入的数据配置,代码如下:
export function initState (vm: Component) {
vm._watchers = []
// 这里的opts 中包含 {el: '#app',data: { message: 'Hello Vue!' }}
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
// 这里有data,初始化data
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
这里面初始化了props、methods、data等,我们的例子中传入了数据,则初始化数据,执行initData()方法;
function initData (vm: Component) {
// 这里的data 为 { message: 'Hello Vue!' }
let data = vm.$options.data
// 组件中建议以data() { return {message: 'Hello Vue!'} }的方式来定义data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
// 不是普通对象则报错
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
// 跟methods、props中的属性对比做校验,保证唯一性进行代理
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
if (props && hasOwn(props, key)) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(key)) {
// 校验成功,且不是保留标签,进行代理
proxy(vm, `_data`, key)
}
}
// observe data 进行响应式操作
observe(data, true /* asRootData */)
}
这里主要分为4步:
proxy(vm, `_data`, key)
export function proxy (target: Object, sourceKey: string, key: string) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
通过defineProperty这个API对vm._data.key 进行代理,这样就可以通过 vm.key的方式访问到定义在data中的属性,方便用户使用
在data的init过程结束后,执行如下代码:
if (vm.$options.el) {
// initData之后 该挂载了
vm.$mount(vm.$options.el);
}
这个$mount在哪定义的呢,在platforms/web/runtime/index.js中有定义
// public mount method
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// el转换成DOM 这里el是 {{ message }}
el = el && inBrowser ? query(el) : undefined
// 执行mountComponent函数
return mountComponent(this, el, hydrating)
}
如果是compiler版本的vue,可以自定义template(我们以这个版本来进行分析),则有如下代码:
// 缓存上面代码的$mount函数
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// 查找元素 这里返回{{ message }}
el = el && query(el)
/* istanbul ignore if */
// 元素不能是body或html
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to or - mount to normal elements instead.`
)
return this
}
// 拿到options
const options = this.$options
// resolve template/el and convert to render function
// render函数 手写render函数则直接跳过这个逻辑, 如果没有写render函数,则分析template,进行编译生成render函数
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函数
const { render, staticRenderFns } = compileToFunctions(template, {
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
// options中生成了属性render函数
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)
}
/**
* Query an element selector if it's not an element already.
*/
function query (el) {
if (typeof el === 'string') {
// 如果el不是元素,是字符串,则在页面中查找这个元素并返回否则报错
var selected = document.querySelector(el);
if (!selected) {
"development" !== 'production' && warn(
'Cannot find element: ' + el
);
return document.createElement('div')
}
return selected
} else {
return el
}
}
这里的操作主要就是将template转换成render函数进行后续操作,其中的编译过程较为麻烦,笔者在后面会出文章进行分析。
接下来执行上面的代码后,最后执行了mountComponent函数,定义在src/core/instance/lifecycle.js中,源码如下:
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
// 这里的el是 {{ message }}
vm.$el = el
if (!vm.$options.render) {
// 如果还没有render,则报错了,必须要有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
)
}
}
}
// 调用生命周期函数beforeMount,挂载前,马上开始挂载了,大家注意!
callHook(vm, 'beforeMount')
let updateComponent
/* istanbul ignore if */
// 性能埋点相关 跳过 执行else逻辑
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)
const vnode = vm._render()
mark(endTag)
measure(`vue ${name} render`, startTag, endTag)
mark(startTag)
vm._update(vnode, hydrating)
mark(endTag)
measure(`vue ${name} patch`, startTag, endTag)
}
} else {
// 定义了updateComponent函数,这是大佬
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
// 实例化watcher,这里叫渲染watcher(RenderWatcher),为渲染而生的watcher
// 注意传入的参数,updateComponent是第二个参数,noop是个空函数
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted) {
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
// 这里是根实例没有 $vnode,所以在实例化Watcher之后,执行mounted生命周期函数
if (vm.$vnode == null) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}
这里面主要是定义了一个updateComponent方法,然后实例化了一个渲染watcher,实例化的过程中干了什么呢,现在来看看这个Watcher的真面目,源码在src/core/observer/watcher.js中:
/* @flow */
let uid = 0
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
export default class Watcher {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
computed: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
dep: Dep;
deps: Array<Dep>;
newDeps: Array<Dep>;
depIds: SimpleSet;
newDepIds: SimpleSet;
before: ?Function;
getter: Function;
value: any;
constructor (
vm: Component, // Vue
expOrFn: string | Function, // 这里是updateComponent
cb: Function, // 空函数noop
options?: ?Object, // before () { if (vm._isMounted) { callHook(vm, 'beforeUpdate') } }
isRenderWatcher?: boolean
) {
this.vm = vm
if (isRenderWatcher) {
// 添加了_watcher属性指向自身,renderWatcher专有属性
vm._watcher = this
}
// 前面定义过的_watchers
vm._watchers.push(this)
// options // before () { if (vm._isMounted) { callHook(vm, 'beforeUpdate')
// 在这次分析中不用看
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.computed = !!options.computed
this.sync = !!options.sync
this.before = options.before
} else {
this.deep = this.user = this.computed = this.sync = false
}
this.cb = cb
this.id = ++uid // uid for batching
this.active = true
this.dirty = this.computed // for computed watchers
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// parse expression for getter
// 上面我没注释的都不用关注, 这里的expOrFn是updateComponent,赋值给this.getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = function () {}
process.env.NODE_ENV !== 'production' && warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
if (this.computed) {
this.value = undefined
this.dep = new Dep()
} else {
// 执行这个get,代码在下面
this.value = this.get()
}
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
// pushTarget这个是收集依赖的,这次分析我们不用关注
pushTarget(this)
let value
const vm = this.vm
try {
// 看这儿,我们执行了this.getter,也就是执行了 updateComponent函数
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
}
开始执行updateComponent,其实就是执行了Vue._update(Vue._render(), false),看上去很简单的一行代码,我们继续分析,首先是执行Vue._render(),这个函数是干什么的?上源码,定义在src/core/instance/render.js中:
export function renderMixin (Vue: Class<Component>) {
// install runtime convenience helpers
installRenderHelpers(Vue.prototype)
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
// 看!在这儿
Vue.prototype._render = function (): VNode {
// 这儿是Vue
const vm: Component = this
// 取出render函数,这个是之前使用template编译而生成的
const { render, _parentVnode } = vm.$options
// reset _rendered flag on slots for duplicate slot check
// 插槽slot相关逻辑 跳过
if (process.env.NODE_ENV !== 'production') {
for (const key in vm.$slots) {
// $flow-disable-line
vm.$slots[key]._rendered = false
}
}
// 插槽slot相关逻辑 跳过
if (_parentVnode) {
vm.$scopedSlots = _parentVnode.data.scopedSlots || emptyObject
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
// 本次分析这是个空
vm.$vnode = _parentVnode
// render self
let vnode
try {
// 开始try了,执行编译生成的render函数,vm._renderProxy这儿是Vue,这儿最终生成了vnode
vnode = render.call(vm._renderProxy, vm.$createElement)
} catch (e) {
handleError(e, vm, `render`)
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
if (vm.$options.renderError) {
try {
vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
} catch (e) {
handleError(e, vm, `renderError`)
vnode = vm._vnode
}
} else {
vnode = vm._vnode
}
} else {
vnode = vm._vnode
}
}
// return empty vnode in case the render function errored out
// 如果生成的vnode不对,是个数组,报错
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
)
}
vnode = createEmptyVNode()
}
// set parent
// 这儿的Vue是根,他没有爸爸
vnode.parent = _parentVnode
// 返回生成的vnode
return vnode
}
}
Vue._render函数最终是要调用render函数生成vnode,就是虚拟节点,虚拟节点是纯js,计算起来比操作Dom要快很多。
vnode = render.call(vm._renderProxy, vm.$createElement)
等同于
vnode = render.call(Vue, Vue.$createElement)
render函数的使用方法,vue的官网有介绍,举个例子,如下代码的template最终被转化成了render函数:
<template> Hello World </template> // 编译成render render(createElement) { return createElement('div', null, "Hello World") }
所以最终就是调用了createElement函数返回vnode,继续分析这儿的Vue.$createElement,源码在src/core/instance/render.js中:
import { createElement } from '../vdom/create-element'
function initRender (vm) {
......
vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
......
}
我们继续找源码:src/core/vdom/create-element.js
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
export function createElement (
context: Component,
tag: any,
data: any,
children: any,
normalizationType: any,
alwaysNormalize: boolean
): VNode | Array<VNode> {
// 类似参数重载,将传入的参数规范化后再执行后面的逻辑
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children
children = data
data = undefined
}
if (isTrue(alwaysNormalize)) {
normalizationType = ALWAYS_NORMALIZE
}
return _createElement(context, tag, data, children, normalizationType)
}
这儿对传入的参数进行了判断,做了规范化,将传入的参数规范化后再执行后面的逻辑,最终调用函数_createElement:
export function _createElement (
context: Component,
tag?: string | Class<Component> | Function | Object,
data?: VNodeData,
children?: any,
normalizationType?: number
): VNode | Array<VNode> {
if (isDef(data) && isDef((data: any).__ob__)) {
process.env.NODE_ENV !== 'production' && warn(
`Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` +
'Always create fresh vnode data objects in each render!',
context
)
return createEmptyVNode()
}
// object syntax in v-bind
if (isDef(data) && isDef(data.is)) {
tag = data.is
}
// 本次我们传入的tag是'div'
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// warn against non-primitive key
if (process.env.NODE_ENV !== 'production' &&
isDef(data) && isDef(data.key) && !isPrimitive(data.key)
) {
if (!__WEEX__ || !('@binding' in data.key)) {
warn(
'Avoid using non-primitive value as key, ' +
'use string/number value instead.',
context
)
}
}
// support single function children as default scoped slot
// 插槽相关逻辑,跳过
if (Array.isArray(children) &&
typeof children[0] === 'function'
) {
data = data || {}
data.scopedSlots = { default: children[0] }
children.length = 0
}
// 这儿的逻辑是将children参数规范化,使其统一格式
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children)
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children)
}
let vnode, ns
// tag是'div',进入逻辑
if (typeof tag === 'string') {
let Ctor
ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
// 判断是否是保留标签
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
)
// 判断当前实例上的options.components中是否存在该标签,渲染组件节点的逻辑
} else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag)
} else {
// 本次进入这个逻辑,new了一个vnode出来
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
vnode = new VNode(
tag, data, children,
undefined, undefined, context
)
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children)
}
if (Array.isArray(vnode)) {
return vnode
} else if (isDef(vnode)) {
if (isDef(ns)) applyNS(vnode, ns)
if (isDef(data)) registerDeepBindings(data)
// 返回vnode
return vnode
} else {
return createEmptyVNode()
}
}
从上面代码可以看出,createElement函数的主要逻辑就是将传入的children参数规范化,然后根据VNode类,生成了一个vnode节点,最终返回这个vnode。
包括两种情况:
1.函数式组件规范化:
// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
// 当子参数包含组件时——因为是函数式组件可能返回一个数组而不是单个根。在这种情况下,只需要简单的
// 标准化——如果任何子参数是一个数组,我们使用Array.prototype.concat将整个数组平整化。
// 它保证只有1级深度因为函数式组件已经规范化了它们自己的子组件。
export function simpleNormalizeChildren (children: any) {
for (let i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
2.嵌套或手写render规范化
// 2. When the children contains constructs that always generated nested Arrays,
// e.g. , , v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
// 2。当子数组包含总是生成嵌套数组的构造时,
// 例如:, , v-for,或者当子节点由用户用手写的渲染函数/ JSX提供时。
// 在这种情况下,需要完全的规范化来满足所有可能类型的子值。
export function normalizeChildren(children: any): ?Array<VNode> {
// 如果是原生类型,直接创建文本节点,否则判断是数组的话,执行normalizeArrayChildren函数
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
/**
* Check if value is primitive
*/
export function isPrimitive (value: any): boolean %checks {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNode> {
const res = []
let i, c, lastIndex, last
// 遍历children
for (i = 0; i < children.length; i++) {
c = children[i]
if (isUndef(c) || typeof c === 'boolean') continue
lastIndex = res.length - 1
last = res[lastIndex]
// nested
if (Array.isArray(c)) {
// 如果子元素是数组且长度大于0,递归调用normalizeArrayChildren
if (c.length > 0) {
c = normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`)
// merge adjacent text nodes
// 这儿做了一个优化,如果子元素的第一个与res的最后一个值都是文本节点,则合并为一个节点
if (isTextNode(c[0]) && isTextNode(last)) {
res[lastIndex] = createTextVNode(last.text + (c[0]: any).text)
c.shift()
}
res.push.apply(res, c)
}
} else if (isPrimitive(c)) {
// 如果是基础属性值且为res的最后一个值为文本节点,将这个值合并到res的最后一个节点上去
if (isTextNode(last)) {
// merge adjacent text nodes
// this is necessary for SSR hydration because text nodes are
// essentially merged when rendered to HTML strings
res[lastIndex] = createTextVNode(last.text + c)
} else if (c !== '') {
// 如果是基础属性值且res的最后一个值不为文本节点,创建一个文本节点推入res中
// convert primitive to vnode
res.push(createTextVNode(c))
}
} else {
// 如果是文本节点,且res的最后一个值也为文本节点,这两个节点合并成一个节点
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
res[lastIndex] = createTextVNode(last.text + c.text)
} else {
// default key for nested array children (likely generated by v-for)
// 嵌套数组的默认key值
if (isTrue(children._isVList) &&
isDef(c.tag) &&
isUndef(c.key) &&
isDef(nestedIndex)) {
c.key = `__vlist${nestedIndex}_${i}__`
}
// 推入res
res.push(c)
}
}
}
return res
}
其实这两个函数主要作用就是将createElement的第三个参数,针对在不同情况生成的children,进行规范化处理,为生成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
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其实就是虚拟节点的简称,通过js模拟真实的DOM节点,我们通过render函数生成虚拟节点的目的,就是为了减少DOM操作,而以js的计算来替代DOM操作,js计算完成后,最后一步再将虚拟节点转换成真实DOM挂载到真正的页面上。
到此为止,我们已经清楚了Vue._render()的目的了,就是生成一个虚拟节点vnode并返回。下一步,就应该执行Vue._update(vnode, hydrating)(hydrating与服务端渲染相关,不用关注,在浏览器端为false)
。
上面我们分析到了执行updateComponent函数了,我们知道Vue._render是返回了一个vnode,我们继续往下分析:
updateComponent = () => {
// 第二个参数是false,这里的vm是Vue
vm._update(vnode, hydrating)
}
Vue._update函数定义在src/core/instance/lifecycle.js中:
export function lifecycleMixin (Vue: Class<Component>) {
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
// 指向Vue
const vm: Component = this
// 这里是div #app
const prevEl = vm.$el
// 下面这几个参数与本次分析关联不大
const prevVnode = vm._vnode
const prevActiveInstance = activeInstance
// Vue实例赋值给activeInstance
activeInstance = vm
// vnode赋值给_vnode
vm._vnode = vnode
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
// 初始渲染 执行__patch__函数
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode)
}
activeInstance = prevActiveInstance
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null
}
if (vm.$el) {
vm.$el.__vue__ = vm
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
}
}
其实_update这个函数的核心逻辑就是执行了__patch__函数,定义在src/platforms/web/runtime/index.js中:
import { patch } from './patch'
// install platform patch function
// 浏览器环境为patch函数
Vue.prototype.__patch__ = inBrowser ? patch : noop
继续查找patch函数,定义在src/platforms/web/runtime/patch.js
/* @flow */
import * as nodeOps from 'web/runtime/node-ops'
import { createPatchFunction } from 'core/vdom/patch'
import baseModules from 'core/vdom/modules/index'
import platformModules from 'web/runtime/modules/index'
// the directive module should be applied last, after all
// built-in modules have been applied.
const modules = platformModules.concat(baseModules)
export const patch: Function = createPatchFunction({ nodeOps, modules })
到这里发现,patch最终是createPatchFunction函数,调用这个函数的时候传入了两个参数,nodeOps,modules,这样做的目的是什么?这里用到了一个函数柯里化的技巧,将不同平台的逻辑对象当做参数传入给了createPatchFunction,这样就避免了最终执行patch函数的时候需要针对不同平台写一堆的判断逻辑,同时这样做代码拆分,也有利于代码维护。
其中nodeOps是封装了各种DOM操作,modules是针对各种属性操作的封装。
我们继续往下看createPatchFunction,定义在src/core/vdom/patch.js中:
const hooks = ['create', 'activate', 'update', 'remove', 'destroy']
export function createPatchFunction (backend) {
let i, j
const cbs = {}
// 拿到传入的对象
const { modules, nodeOps } = backend
// 这个地方是将modules上定义的跟class,style,events相关的hooks函数推入cbs对象统一管理
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = []
for (j = 0; j < modules.length; ++j) {
if (isDef(modules[j][hooks[i]])) {
cbs[hooks[i]].push(modules[j][hooks[i]])
}
}
}
......(这之中定义了很多辅助函数)
// 执行的__patch__最终就是这个函数,本次传入的参数分别为(div#app, vnode,false,false)
return function patch (oldVnode, vnode, hydrating, removeOnly) {
// 未定义vnode,则进入这个逻辑
if (isUndef(vnode)) {
if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
return
}
let isInitialPatch = false
const insertedVnodeQueue = []
// oldVnode有定义,进入else逻辑
if (isUndef(oldVnode)) {
// empty mount (likely as component), create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
// 判断oldvnode是否是真实DOM节点
const isRealElement = isDef(oldVnode.nodeType)
// 不是真实节点的时候,进入diff算法,与本次分析无关
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
// 是真实节点,本次进入这个逻辑
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
// 服务器渲染的逻辑,与本次分析无关
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
oldVnode.removeAttribute(SSR_ATTR)
hydrating = true
}
// 服务器渲染的逻辑,与本次分析无关
if (isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
', or missing
. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
// 将真实DOM当参数传入,创建一个空vnode
oldVnode = emptyNodeAt(oldVnode)
}
// replacing existing element
// oldElm为div
const oldElm = oldVnode.elm
// nodeOps.parentNode是查找传入元素的父元素,这里的parentElm为body
const parentElm = nodeOps.parentNode(oldElm)
// create new node
// 创建新的真实节点,本次分析这段逻辑比较重要
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
)
// update parent placeholder node element, recursively
// 递归地更新父占位符节点元素,本次分析的节点是根节点,没有parent
if (isDef(vnode.parent)) {
let ancestor = vnode.parent
const patchable = isPatchable(vnode)
while (ancestor) {
for (let i = 0; i < cbs.destroy.length; ++i) {
cbs.destroy[i](ancestor)
}
ancestor.elm = vnode.elm
if (patchable) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, ancestor)
}
// #6513
// invoke insert hooks that may have been merged by create hooks.
// e.g. for directives that uses the "inserted" hook.
const insert = ancestor.data.hook.insert
if (insert.merged) {
// start at index 1 to avoid re-invoking component mounted hook
for (let i = 1; i < insert.fns.length; i++) {
insert.fns[i]()
}
}
} else {
registerRef(ancestor)
}
ancestor = ancestor.parent
}
}
// destroy old node
// 本次分析的parentElm是body元素
if (isDef(parentElm)) {
// 移除旧元素
removeVnodes(parentElm, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
// 调用钩子函数
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
将虚拟节点生成的真实元素返回
return vnode.elm
}
到这儿我们可以看出,patch的整个逻辑就是将vnode转换成真实的DOM,创建了一个新的DOM节点,并删除了旧的DOM节点,核心逻辑是调用了createElm()这个函数,我们继续分析createELm,源码如下:
createELm
function createElm (
vnode,
insertedVnodeQueue,
parentElm,
refElm,
nested,
ownerArray,
index
) {
// 创建的是个空vnode,未定义elm
if (isDef(vnode.elm) && isDef(ownerArray)) {
// This vnode was used in a previous render!
// now it's used as a new node, overwriting its elm would cause
// potential patch errors down the road when it's used as an insertion
// reference node. Instead, we clone the node on-demand before creating
// associated DOM element for it.
vnode = ownerArray[index] = cloneVNode(vnode)
}
// 这是true
vnode.isRootInsert = !nested // for transition enter check
// 有组件节点进入这个逻辑,本次分析不涉及
if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
return
}
// data为{ attrs:{ id: "app" } }
const data = vnode.data
// children为textNode
const children = vnode.children
// tag为'div
const tag = vnode.tag
// tag有定义
if (isDef(tag)) {
// 判断元素是否存在
if (process.env.NODE_ENV !== 'production') {
if (data && data.pre) {
creatingElmInVPre++
}
if (isUnknownElement(vnode, creatingElmInVPre)) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
)
}
}
// 创建真实DOM元素div
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode)
setScope(vnode)
/* istanbul ignore if */
// __WEEX__平台逻辑,跳过,执行else逻辑
if (__WEEX__) {
// in Weex, the default insertion order is parent-first.
// List items can be optimized to use children-first insertion
// with append="tree".
const appendAsTree = isDef(data) && isTrue(data.appendAsTree)
if (!appendAsTree) {
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
insert(parentElm, vnode.elm, refElm)
}
createChildren(vnode, children, insertedVnodeQueue)
if (appendAsTree) {
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
insert(parentElm, vnode.elm, refElm)
}
} else {
// 进入else逻辑,创建子节点,这里的children是文本节点textNode,这里面递归创建子节点最终最终插入到div#app元素上
createChildren(vnode, children, insertedVnodeQueue)
// 调用create钩子函数
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
// 执行插入操作,插入到body元素
insert(parentElm, vnode.elm, refElm)
}
if (process.env.NODE_ENV !== 'production' && data && data.pre) {
creatingElmInVPre--
}
} else if (isTrue(vnode.isComment)) {
// tag未定义的情况下,如果是注释节点,创建注释节点
vnode.elm = nodeOps.createComment(vnode.text)
insert(parentElm, vnode.elm, refElm)
} else {
// tag未定义的情况下,如果不是注释节点,只可能是文本节点,创建文本节点,插入到div#app后面,本次分析递归执行了createElm函数,创建了子节点,并执行了插入操作
vnode.elm = nodeOps.createTextNode(vnode.text)
insert(parentElm, vnode.elm, refElm)
}
}
createChildren
createChildren的源码如下:
function createChildren (vnode, children, insertedVnodeQueue) {
// 如果children是数组,遍历children,本次进入该逻辑:
if (Array.isArray(children)) {
if (process.env.NODE_ENV !== 'production') {
checkDuplicateKeys(children);
}
// 递归调用createElm函数,创建子节点,并执行插入:
for (var i = 0; i < children.length; ++i) {
createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i);
}
// 如果是vnode的text是原生类型数据,进入该逻辑:
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)));
}
}
由以上逻辑可以看出,createElm函数在本次场景中,执行了两次:
1.首次进入时,tag有定义,会创建真实DOM元素div#app,再执行createChildren函数,遍历vnode.children数组,递归执行createElm函数;
2.这样就进入了第二次执行,这时候的children是文本节点,未定义tag,进入else逻辑,创建了文本节点,并将文本节点插入到div#app元素上面,完成文本节点的createElm;
3.继续进入第一次createElm函数剩下的逻辑,将插入文本节点的div#app插入到了body元素上面,这样页面上就存在了两个div#app的DOM元素了,从这里,我们也清楚了,DOM的创建是从子到父的一个过程;
4.完成DOM元素的创建并挂载后,再将之前的旧div#app元素给移除,这样,整个文本节点挂载到页面的流程我们就基本清楚了。
接下来做个简单的总结。
3.总结
对于以下代码:
<template>
<div id="app">
{{ message }}
</div>
</template>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
渲染的流程大致如下:
第一步执行数据等流程初始化(init);
第二步执行$mount函数,将template模板进行编译,生成render函数(mount:template => render);
第三步编译完成后,调用mountComponent函数,生成updateComponent函数,实例化了一个渲染watcher,执行updateComponent函数(mount:new Watcher);
第四步执行render函数,内部是调用了createElement函数,最终生成vnode(render => vnode);
第五步将vnode作为参数,执行_update函数,主要核心是patch函数,patch函数中最重要的是createElm函数,将vnode转化成真实DOM节点并挂载到页面(patch);
init
$mount
template => render
vnode
patch
DOM
你可能感兴趣的:(javascript,vue.js,前端,源码,前端框架)