国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

vue數(shù)據(jù)控制視圖源碼解析

2019-11-19 14:06:06
字體:
供稿:網(wǎng)友

分析vue是如何實現(xiàn)數(shù)據(jù)改變更新視圖的.

前記

三個月前看了vue源碼來分析如何做到響應(yīng)式數(shù)據(jù)的, 文章名字叫vue源碼之響應(yīng)式數(shù)據(jù), 最后分析到, 數(shù)據(jù)變化后會調(diào)用Watcher的update()方法. 那么時隔三月讓我們繼續(xù)看看update()做了什么. (這三個月用react-native做了個項目, 也無心總結(jié)了, 因為好像太簡單了).

本文敘事方式為樹藤摸瓜, 順著看源碼的邏輯走一遍, 查看的vue的版本為2.5.2. 我fork了一份源碼用來記錄注釋.

目的

明確調(diào)查方向才能直至目標(biāo), 先說一下目標(biāo)行為: 數(shù)據(jù)變化以后執(zhí)行了什么方法來更新視圖的. 那么準(zhǔn)備開始以這個方向為目標(biāo)從vue源碼的入口開始找答案.

從之前的結(jié)論開始

先來復(fù)習(xí)一下之前的結(jié)論:

vue構(gòu)造的時候會在data(和一些別的字段)上建立Observer對象, getter和setter被做了攔截, getter觸發(fā)依賴收集, setter觸發(fā)notify.

另一個對象是Watcher, 注冊watch的時候會調(diào)用一次watch的對象, 這樣觸發(fā)了watch對象的getter, 把依賴收集到當(dāng)前Watcher的deps里, 當(dāng)任何dep的setter被觸發(fā)就會notify當(dāng)前Watcher來調(diào)用Watcher的update()方法.

那么這里就從注冊渲染相關(guān)的Watcher開始.

找到了文件在src/core/instance/lifecycle.js中.

new Watcher(vm, updateComponent, noop, null, true /* isRenderWatcher */)

mountComponent

渲染相關(guān)的Watcher是在mountComponent()這個方法中調(diào)用的, 那么我們搜一下這個方法是在哪里調(diào)用的. 只有2處, 分別是src/platforms/web/runtime/index.js和src/platforms/weex/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)}

原來如此, 是$mount()方法調(diào)用了mountComponent(), (或者在vue構(gòu)造時指定el字段也會自動調(diào)用$mount()方法), 因為web和weex(什么是weex?之前別的文章介紹過)渲染的標(biāo)的物不同, 所以在發(fā)布的時候應(yīng)該引入了不同的文件最后發(fā)不成不同的dist(這個問題留給之后來研究vue的整個流程).

下面是mountComponent方法:

export function mountComponent ( vm: Component, el: ?Element, hydrating?: boolean): Component { vm.$el = el // 放一份el到自己的屬性里 if (!vm.$options.render) { // render應(yīng)該經(jīng)過處理了, 因為我們經(jīng)常都是用template或者vue文件 // 判斷是否存在render函數(shù), 如果沒有就把render函數(shù)寫成空VNode來避免紅錯, 并報出黃錯 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') let updateComponent /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { // 不看這里的代碼了, 直接看else里的, 行為是一樣的 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 = () => {  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 new Watcher(vm, updateComponent, noop, null, true /* isRenderWatcher */) hydrating = false // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true callHook(vm, 'mounted') } return vm}

這段代碼其實只做了3件事:

  • 調(diào)用beforeMount鉤子
  • 建立Watcher
  • 調(diào)用mounted鉤子

(哈哈哈)那么其實核心就是建立Watcher了.

看一下Watcher的參數(shù): vm是this, updateComponent是一個函數(shù), noop是空, null是空, true代表是RenderWatcher.

在Watcher里看了isRenderWatcher:

if (isRenderWatcher) {  vm._watcher = this }

是的, 只是復(fù)制了一份用來在watcher第一次patch的時候判斷一些東西(從注釋里看的, 我現(xiàn)在還不知道是干嘛的).

那么只有一個問題沒解決就是updateComponent是個什么東西.

updateComponent

在Watcher的構(gòu)造函數(shù)的第二個參數(shù)傳了function, 那么這個函數(shù)就成了watcher的getter. 聰明的你應(yīng)該已經(jīng)猜到, 在這個updateComponent里一定調(diào)用了視圖中所有的數(shù)據(jù)的getter, 才能在watcher中建立依賴從而讓視圖響應(yīng)數(shù)據(jù)的變化.

updateComponent = () => {  vm._update(vm._render(), hydrating) }

那么就去找vm._update()和vm._render().

在src/core/instance/render.js找到了._render()方法.

Vue.prototype._render = function (): VNode { const vm: Component = this const { render, _parentVnode } = vm.$options // todo: render和_parentVnode的由來 // reset _rendered flag on slots for duplicate slot check if (process.env.NODE_ENV !== 'production') {  for (const key in vm.$slots) {  // $flow-disable-line  vm.$slots[key]._rendered = false  } } 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 {  vnode = render.call(vm._renderProxy, vm.$createElement) } catch (e) {  // catch其實不需要看了, 都是做異常處理, _vnode是在vm._update的時候保存的, 也就是上次的狀態(tài)或是null(init的時候給的)  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 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 vnode.parent = _parentVnode return vnode }}

這個方法做了:

  • 根據(jù)當(dāng)前vm的render方法來生成VNode. (render方法可能是根據(jù)template或vue文件編譯而來, 所以推論直接寫render方法效率最高)
  • 如果render方法有問題, 那么首先調(diào)用renderError方法, 再不行就讀取上次的vnode或是null.
  • 如果有父節(jié)點就放到自己的.parent屬性里.
  • 最后返回VNode

所以核心是這句:

vnode = render.call(vm._renderProxy, vm.$createElement)

其中的render(), vm._renderProxy, vm.$createElement都不知道是什么.

先看vm._renderProxy: 是initMixin()的時候設(shè)置的, 在生產(chǎn)環(huán)境返回vm, 開發(fā)環(huán)境返回代理, 那么我們認(rèn)為他是一個可以debug的vm(就是vm), 細節(jié)之后再看.

vm.$createElement的代碼在vdom文件夾下, 看了下是一個方法, 返回值一個VNode.

render有點復(fù)雜, 能不能以后研究, 總之就是把template或者vue單文件和mount目標(biāo)parse成render函數(shù).

小總結(jié): vm._render()的返回值是VNode, 根據(jù)當(dāng)前vm的render函數(shù)

接下來看vm._update()

Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) { const vm: Component = this if (vm._isMounted) {  callHook(vm, 'beforeUpdate') } // 記錄update之前的狀態(tài) const prevEl = vm.$el const prevVnode = vm._vnode const prevActiveInstance = activeInstance activeInstance = vm vm._vnode = vnode // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // 初次加載, 只有_update方法更新vm._vnode, 初始化是null  // initial render  vm.$el = vm.__patch__( // patch創(chuàng)建新dom  vm.$el, vnode, hydrating, false /* removeOnly */,  vm.$options._parentElm,  vm.$options._refElm  )  // no need for the ref nodes after initial patch  // this prevents keeping a detached DOM tree in memory (#5851)  vm.$options._parentElm = vm.$options._refElm = null } else {  // updates  vm.$el = vm.__patch__(prevVnode, vnode) // patch更新dom } 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. }

我們關(guān)心的部分其實就是__patch()的部分, __patch()做了對dom的操作, 在_update()里判斷了是否是初次調(diào)用, 如果是的話創(chuàng)建新dom, 不是的話傳入新舊node進行比較再操作.

結(jié)論

vue的視圖渲染是一種特殊的Watcher, watch的內(nèi)容是一個函數(shù), 函數(shù)運行的過程調(diào)用了render函數(shù), render又是由template或者el的dom編譯成的(template中含有一些被observe的數(shù)據(jù)). 所以template中被observe的數(shù)據(jù)有變化觸發(fā)Watcher的update()方法就會重新渲染視圖.

遺留

render函數(shù)是在哪里被編譯的
vue源碼發(fā)布時引入不同平臺最后打成dist的流程是什么
__patch__和VNode的分析

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 清新县| 南川市| 华坪县| 宁武县| 承德县| 麦盖提县| 阿拉善盟| 溧水县| 东乌珠穆沁旗| 江孜县| 黔江区| 泰来县| 福贡县| 安泽县| 康保县| 东乡县| 津市市| 福贡县| 柘城县| 肇庆市| 疏附县| 博罗县| 抚顺县| 射洪县| 桃园县| 四平市| 龙泉市| 长治市| 岳西县| 永川市| 额敏县| 百色市| 孟州市| 嘉定区| 华亭县| 平泉县| 长岛县| 望江县| 揭阳市| 封开县| 承德市|