vue官方對響應式原理的解釋:深刻響應式原理javascript
上一節講了VUE中依賴收集和依賴觸發的原理,然鵝對響應式的總體流程咱們仍是有不少疑問:html
爲了回答以上的幾個問題,咱們不得不梳理一波VUE響應式的總體流程了vue
vue源碼的 instance/init.js 中是初始化的入口,其中初始化中除了初始化的幾個步驟之外,在最後有這樣一段 代碼:java
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
複製代碼
在初始化結束後,調用options.el中。node
關於$mount的定義在兩處能夠看到:platforms/web/runtime/index.js、platforms/web/entry-runtime-with-compiler.jsreact
其中runtime/index.js的代碼以下:web
Vue.prototype.$mount = function ( el?: string | Element, hydrating?: boolean ): Component {
el = el && inBrowser ? query(el) : undefined
// 劃重點!!!
return mountComponent(this, el, hydrating)
}
複製代碼
runtime/index.js是運行時vue的入口,其中定義的mount功能,其中主要調用了mountComponent()函數完成掛載。 entry-runtime-with-compiler.js是完整的vue的入口,在運行時vue的$mount基礎上加入了編譯模版的能力。express
entry-runtime-with-compiler.js中定義了mount()的基礎上添加了模版編譯。代碼以下:ide
Vue.prototype.$mount = function ( el?: string | Element, hydrating?: boolean ): Component {
el = el && query(el)
//檢查掛載點是否是<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
// 判斷渲染函數不存在時
if (!options.render) {
...//構建渲染函數
}
//調用運行時vue的$mount()函數,
return mount.call(this, el, hydrating)
}
複製代碼
entry-runtime-with-compiler.js中的$mount()函數主要作了三件事:函數
上述第二步,若渲染函數不存在時,構建渲染函數,代碼以下:
let template = options.template
//若是template存在,則經過template獲取真正的【模版】
if (template) {
//template是字符串
if (typeof template === 'string') {
//template第一個字符是#,則將該字符串做爲id選擇器獲取對應元素做爲【模版】
if (template.charAt(0) === '#') {
template = idToTemplate(template)
... //省略
}
//若是template是元素節點,則將template的innerHTML做爲【模版】
} else if (template.nodeType) {
template = template.innerHTML
//若template無效,則顯示提示
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
//若template不存在,則將el元素的outerHTML做爲【模版】
} else if (el) {
template = getOuterHTML(el)
}
//此時template中是最終的【模版】,下面根據【模版】生成rander函數
if (template) {
... //省略
// 劃重點!!!
// 使用compileToFunctions函數將【模版】template,編譯成爲渲染函數。
const { render, staticRenderFns } = compileToFunctions(template, {
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
... //省略
}
複製代碼
建立渲染函數階段主要作了兩件事:
上一步確保渲染函數render()存在後,就進入到了這正的掛載階段。前面講到掛載函數主要在mountComponent()中完成。
mountComponent()函數的定義在src/core/instance/lifecycle.js文件中。代碼以下:
export function mountComponent ( vm: Component, el: ?Element, hydrating?: boolean ): Component {
vm.$el = el
//若是render不存在
if (!vm.$options.render) {
//爲render賦初始值,並打印warning提示信息
vm.$options.render = createEmptyVNode
... //省略
}
}
//觸發beforeMount鉤子
callHook(vm, 'beforeMount')
// 開始掛載
let updateComponent
/* istanbul ignore if */
// 定義並初始化updateComponent函數
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)
// 調用_render函數生成vnode虛擬節點
const vnode = vm._render()
mark(endTag)
measure(`vue ${name} render`, startTag, endTag)
mark(startTag)
// 以虛擬節點vnode做爲參數調用_update函數,生成真正的DOM
vm._update(vnode, hydrating)
mark(endTag)
measure(`vue ${name} patch`, startTag, endTag)
}
} else {
updateComponent = () => {
//調用_render函數生成vnode虛擬節點;以虛擬節點vnode做爲參數調用_update函數,生成真正的DOM
vm._update(vm._render(), hydrating)
}
}
複製代碼
mountComponent主要作了三件事:
watcher類的定義在core/observer/watcher.js中,代碼以下:
export default class Watcher {
... //
// 構造函數
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
if (isRenderWatcher) {
// 將渲染函數的觀察者存入_watcher
vm._watcher = this
}
//將全部觀察者push到_watchers列表
vm._watchers.push(this)
// options
if (options) {
// 是否深度觀測
this.deep = !!options.deep
// 是否爲開發者定義的watcher(渲染函數觀察者、計算屬性觀察者屬於內部定義的watcher)
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 = []
// depIds 和 newDepIds 用書避免重複收集依賴
this.depIds = new Set()
this.newDepIds = new Set()
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// parse expression for getter
// 兼容被觀測數據,當被觀測數據是function時,直接將其做爲getter
// 當被觀測數據不是function時經過parsePath解析其真正的返回值
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 {
// 除計算屬性的觀察者之外的全部觀察者調用this.get()方法
this.value = this.get()
}
}
// get方法
get () {
...
}
// 添加依賴
addDep (dep: Dep) {
...
}
// 移除廢棄觀察者;清空newDepIds 屬性和 newDeps 屬性的值
cleanupDeps () {
...
}
// 當依賴變化時,觸發更新
update () {
...
}
// 數據變化函數的入口
run () {
...
}
// 真正進行數據變化的函數
getAndInvoke (cb: Function) {
...
}
//
evaluate () {
...
}
//
depend () {
...
}
//
teardown () {
...
}
}
複製代碼
由以上代碼可見,在watcher構造函數中作了以下幾件事:
get中的代碼以下:
get () {
// 將觀察者對象保存至Dep.target中(Dep.target在上一章提到過)
pushTarget(this)
let value
const vm = this.vm
try {
//調用getter方法,得到被觀察目標的值
value = this.getter.call(vm, vm)
} catch (e) {
...
} finally {
...
}
return value
}
複製代碼
get()函數中主要作了以下幾件事:
// 添加依賴
addDep (dep: Dep) {
const id = dep.id
// newDepIds避免本次get中重複收集依賴
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
// 避免屢次求值中重複收集依賴,每次求值以後newDepIds會被清空,所以須要depIds來判斷。newDepIds中清空
if (!this.depIds.has(id)) {
dep.addSub(this)
}
}
}
複製代碼
根據上一章和本章的講解,總結一下響應式的總體流程: 假設有模版:
<div id="test">
{{str}}
</div>
複製代碼
至此響應式過程完成。
參考文章:揭開數據響應系統的面紗