vue 源碼深入學習分析——史上超詳細


2017/6/2 15:27:50 第一次復習

vue 框架號稱五分鍾就能上手,半小時就能精通,這是因為其使用非常簡單,就像下面一樣:
   
   
   
           
  1. let vm = new Vue({
  2. el: '#app',
  3. data: {
  4. a: 1,
  5. b: [1, 2, 3]
  6. }
  7. })
在最開始,我傳遞了兩個選項 el 以及 data ,很簡單,官網上也是這樣寫的。
你肯定注意到了,我使用了 new 操作符。這就很自然的想到,Vue 就是一個構造函數,vm是 Vue構造函數 生成的實例,我們的配置項是傳入構造函數的參數,是一個包括 el 屬性 和 data屬性的對象,事實上在實例化 Vue 時,傳入的選項對象可以包含 數據、模板、掛載元素、方法、生命周期鈎子等選項。全部的選項可以在 vue的官方API 文檔中查看。;

那么我們下面就要受好奇心的驅動,來看看 Vue構造函數 是什么樣的?

在  \node_modules\vue\src\core\instance\index.js  文件里面,是下面的代碼:
   
   
   
           
  1. import { initMixin } from './init'
  2. import { stateMixin } from './state'
  3. import { renderMixin } from './render'
  4. import { eventsMixin } from './events'
  5. import { lifecycleMixin } from './lifecycle'
  6. import { warn } from '../util/index'
  7. function Vue (options) {
  8. if (process.env.NODE_ENV !== 'production' &&
  9. !(this instanceof Vue)) {
  10. warn('Vue is a constructor and should be called with the `new` keyword')
  11. }
  12. this._init(options)
  13. }
  14. initMixin(Vue)
  15. stateMixin(Vue)
  16. eventsMixin(Vue)
  17. lifecycleMixin(Vue)
  18. renderMixin(Vue)
  19. export default V
不用害怕,我帶你捋一捋,我們首先關注第8行,我摘抄出來:
   
   
   
           
  1. function Vue (options) {
  2. if (process.env.NODE_ENV !== 'production' && // 這個 if 判斷,是當你不用new操作符來實例化Vue構造函數時,會爆出警告
  3. !(this instanceof Vue)) {
  4. warn('Vue is a constructor and should be called with the `new` keyword')
  5. }
  6. this._init(options) // 主要就是這一句,
  7. }
發現了吧,Vue 的確是一個構造函數,和你平時使用的 Array, Object 等普普通通的構造函數,沒有本質的區別。
在構造函數里面,我們要關心的是 this._init( options ) , 稍微我會詳細的來講,我們先看   \node_modules\vue\src\core\instance\index.js  文件中的第16行~20行:
   
   
   
           
  1. initMixin(Vue)
  2. stateMixin(Vue)
  3. eventsMixin(Vue)
  4. lifecycleMixin(Vue)
  5. renderMixin(Vue)
上面的代碼調用了五個方法,這五個方法都是把Vue構造函數作為參數傳入,其目的都是  Vue .prototype  上掛載方法或屬性,這個概念很好理解,我們在js 的原型鏈繼承的學習中,經常把屬性和方法丟到構造函數的原型上作為公有的屬性和方法。
   
   
   
           
  1. // initMixin(Vue) src/core/instance/init.js **************************************************
  2. Vue.prototype._init = function (options?: Object) {}
  3. // stateMixin(Vue) src/core/instance/state.js **************************************************
  4. Vue.prototype.$data
  5. Vue.prototype.$set = set
  6. Vue.prototype.$delete = del
  7. Vue.prototype.$watch = function(){}
  8. // renderMixin(Vue) src/core/instance/render.js **************************************************
  9. Vue.prototype.$nextTick = function (fn: Function) {}
  10. Vue.prototype._render = function (): VNode {}
  11. Vue.prototype._s = _toString
  12. Vue.prototype._v = createTextVNode
  13. Vue.prototype._n = toNumber
  14. Vue.prototype._e = createEmptyVNode
  15. Vue.prototype._q = looseEqual
  16. Vue.prototype._i = looseIndexOf
  17. Vue.prototype._m = function(){}
  18. Vue.prototype._o = function(){}
  19. Vue.prototype._f = function resolveFilter (id) {}
  20. Vue.prototype._l = function(){}
  21. Vue.prototype._t = function(){}
  22. Vue.prototype._b = function(){}
  23. Vue.prototype._k = function(){}
  24. // eventsMixin(Vue) src/core/instance/events.js **************************************************
  25. Vue.prototype.$on = function (event: string, fn: Function): Component {}
  26. Vue.prototype.$once = function (event: string, fn: Function): Component {}
  27. Vue.prototype.$off = function (event?: string, fn?: Function): Component {}
  28. Vue.prototype.$emit = function (event: string): Component {}
  29. // lifecycleMixin(Vue) src/core/instance/lifecycle.js **************************************************
  30. Vue.prototype._mount = function(){}
  31. Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {}
  32. Vue.prototype._updateFromParent = function(){}
  33. Vue.prototype.$forceUpdate = function () {}
  34. Vue.prototype.$destroy = function () {}
經過上面5個方法對Vue構造函數的處理,vm實例上就可以使用這些屬性和方法了。其實在其他地方,Vue 構造函數也被處理了:在 src/core/index.js 文件中:
    
    
    
            
  1. import Vue from './instance/index'
  2. import { initGlobalAPI } from './global-api/index'
  3. import { isServerRendering } from 'core/util/env'
  4. initGlobalAPI(Vue)
  5. Object.defineProperty(Vue.prototype, '$isServer', { //為 Vue.prototype 添加$isServer屬性
  6. get: isServerRendering
  7. })
  8. Vue.version = '__VERSION__' // 在VUE 身上掛載了 version的靜態屬性
  9. export default Vue
initGlobalAPI() 的作用是在 Vue 構造函數上掛載靜態屬性和方法,Vue 在經過 initGlobalAPI 之后,會變成這樣:
    
    
    
            
  1. Vue.config
  2. Vue.util = util
  3. Vue.set = set
  4. Vue.delete = del
  5. Vue.nextTick = util.nextTick
  6. Vue.options = {
  7. components: {
  8. KeepAlive
  9. },
  10. directives: {},
  11. filters: {},
  12. _base: Vue
  13. }
  14. Vue.use
  15. Vue.mixin
  16. Vue.cid = 0
  17. Vue.extend
  18. Vue.component = function(){}
  19. Vue.directive = function(){}
  20. Vue.filter = function(){}
  21. Vue.prototype.$isServer
  22. Vue.version = '__VERSION__'
下一個就是 web-runtime.js 文件了, web-runtime.js 文件主要做了三件事兒:
    
    
    
            
  1. 1、覆蓋 Vue.config 的屬性,將其設置為平台特有的一些方法
  2. 2Vue.options.directives Vue.options.components 安裝平台特有的指令和組件
  3. 3、在 Vue.prototype 上定義 __patch__ $mount
經過 web-runtime.js 文件之后,Vue 變成下面這個樣子:
    
    
    
            
  1. // 安裝平台特定的utils
  2. Vue.config.isUnknownElement = isUnknownElement
  3. Vue.config.isReservedTag = isReservedTag
  4. Vue.config.getTagNamespace = getTagNamespace
  5. Vue.config.mustUseProp = mustUseProp
  6. // 安裝平台特定的 指令 和 組件
  7. Vue.options = {
  8. components: {
  9. KeepAlive,
  10. Transition,
  11. TransitionGroup
  12. },
  13. directives: {
  14. model,
  15. show
  16. },
  17. filters: {},
  18. _base: Vue
  19. }
  20. Vue.prototype.__patch__
  21. Vue.prototype.$mount
這里要注意的是Vue.options 的變化。
最后一個處理 Vue 的文件就是入口文件 web-runtime-with-compiler.js 了,該文件做了兩件事:
1、緩存來自 web-runtime.js 文件的 $mount 函數
    
    
    
            
  1. const mount = Vue.prototype.$mount
2、在 Vue 上掛載 compile
    
    
    
            
  1. Vue.compile = compileToFunctions
上面 compileToFunctions 函數可以將模板 template 編譯為render函數。
至此,我們算是還原了 Vue 構造函數,總結一下:
    
    
    
            
  1. 1Vue.prototype 下的屬性和方法的掛載主要是在 src/core/instance 目錄中的代碼處理的
  2. 2Vue 下的靜態屬性和方法的掛載主要是在 src/core/global-api 目錄下的代碼處理的
  3. 3web-runtime.js 主要是添加web平台特有的配置、組件和指令,web-runtime-with-compiler.js Vue $mount 方法添加 compiler 編譯器,支持 template

好了,我們再回過頭來看 this._init() 方法,_init() 方法就是Vue調用的第一個方法,然后將我們的參數 options 傳了過去。_init() 是在   \node_modules\vue\src\core\instance\init.js 文件中被聲明的:
    
    
    
            
  1. Vue.prototype._init = function (options?: Object) {
  2. const vm: Component = this
  3. // a uid
  4. vm._uid = uid++
  5. let startTag, endTag
  6. /* istanbul ignore if */
  7. if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
  8. startTag = `vue-perf-init:${vm._uid}`
  9. endTag = `vue-perf-end:${vm._uid}`
  10. mark(startTag)
  11. }
  12. // a flag to avoid this being observed
  13. vm._isVue = true
  14. // merge options
  15. if (options && options._isComponent) {
  16. // optimize internal component instantiation
  17. // since dynamic options merging is pretty slow, and none of the
  18. // internal component options needs special treatment.
  19. initInternalComponent(vm, options)
  20. } else { // 大部分情況下是走了這個分支,也是vue第一步要做的事情,使用mergeOptions來合並參數選項
  21. vm.$options = mergeOptions(
  22. resolveConstructorOptions(vm.constructor),
  23. options || {},
  24. vm
  25. )
  26. }
  27. /* istanbul ignore else */
  28. if (process.env.NODE_ENV !== 'production') {
  29. initProxy(vm)
  30. } else {
  31. vm._renderProxy = vm
  32. }
  33. // expose real self
  34. vm._self = vm
  35. initLifecycle(vm)
  36. initEvents(vm)
  37. initRender(vm)
  38. callHook(vm, 'beforeCreate')
  39. initInjections(vm) // resolve injections before data/props
  40. initState(vm)
  41. initProvide(vm) // resolve provide after data/props
  42. callHook(vm, 'created')
  43. /* istanbul ignore if */
  44. if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
  45. vm._name = formatComponentName(vm, false)
  46. mark(endTag)
  47. measure(`${vm._name} init`, startTag, endTag)
  48. }
  49. if (vm.$options.el) {
  50. vm.$mount(vm.$options.el)
  51. }
  52. }
好了,我們一開始不需要關心那么多邊邊角角,直接從23行代碼開始看,因為大部分情況下是走了這條分支,也就是執行了下面的代碼:
    
    
    
            
  1. vm.$options = mergeOptions(
  2. resolveConstructorOptions(vm.constructor),
  3. options || {},
  4. vm
  5. )
這里是執行了 mergeOptions 函數,並將返回值賦值給 vm.$options  屬性。 mergeOptions 函數接受三個參數,分別是 resolveContructorOptions方法,   我們調用 vue 構造函數傳入的配置對象(如果沒有就是空對象),以及 vm 實例 本身。

我們先看 resovleContructorOptions 方法, 傳入的參數是 vm.constructor 。 vm.constructor 代表的是啥?  const vm : Component = this 人家_init() 函數第一行就定義了,是指向_init() 函數內部的this, _init( ) 函數是 Vue.prototype上的一個方法,所以在其身上調用的時候,this 指向本身  Vue.prototype, 那么 vm.constructor 也就是指向 Vue 構造函數.
   
   
   
           
  1. export function resolveConstructorOptions (Ctor: Class<Component>) { //ctor 就是 VUE 構造函數
  2. let options = Ctor.options // vue 構造函數身上的 options 屬性
  3. if (Ctor.super) { // 判斷是否定義了 Vue.super ,這個是用來處理繼承的,我們后續再講
  4. const superOptions = resolveConstructorOptions(Ctor.super)
  5. const cachedSuperOptions = Ctor.superOptions
  6. if (superOptions !== cachedSuperOptions) {
  7. // super option changed,
  8. // need to resolve new options.
  9. Ctor.superOptions = superOptions
  10. // check if there are any late-modified/attached options (#4976)
  11. const modifiedOptions = resolveModifiedOptions(Ctor)
  12. // update base extend options
  13. if (modifiedOptions) {
  14. extend(Ctor.extendOptions, modifiedOptions)
  15. }
  16. options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
  17. if (options.name) {
  18. options.components[options.name] = Ctor
  19. }
  20. }
  21. }
  22. return options
  23. }
第22行, resolveConstructorOptions 方法直接返回了 Vue.options。也就是說,傳遞給 mergeOptions 方法的第一個參數其實是 Vue.options。那么,實際上原來的代碼就變成了下面這樣:
   
   
   
           
  1. // 這是原來的代碼
  2. vm.$options = mergeOptions(
  3. resolveConstructorOptions(vm.constructor),
  4. options || {},
  5. vm
  6. )

  7.  
  8. // 實際上傳過去的參數是下面這些
  9. vm.$options = mergeOptions(
  10. // Vue.options
  11. {
  12. components: {
  13. KeepAlive,
  14. Transition,
  15. TransitionGroup
  16. },
  17. directives: {
  18. model,
  19. show
  20. },
  21. filters: {},
  22. _base: Vue
  23. },
  24. // 調用Vue構造函數時傳入的參數選項 options
  25. {
  26. el: '#app',
  27. data: {
  28. a: 1,
  29. b: [1, 2, 3]
  30. }
  31. },
  32. // this
  33. vm
  34. )
為什么要使用 mergeOptions 方法呢? 是為了 合並策略, 對於子組件和父組件如果有相同的屬性(option)時要進行合並,相關文章:
那么我們繼續查看 _init() 方法在合並完選項之后,Vue 第二部做的事情就來了:初始化工作與Vue實例對象的設計:





通過initData 看vue的數據響應系統
Vue的數據響應系統包含三個部分: Observer Dep Watcher 。我們還是先看一下 initData 中的代碼:
    
    
    
            
  1. function initData (vm: Component) {
  2. let data = vm.$options.data // 第一步還是要先拿到數據,vm.$options.data 這時候還是通過 mergeOptions 合並處理后的 mergedInstanceDataFn 函數
  3. data = vm._data = typeof data === 'function'
  4. ? data.call(vm)
  5. : data || {}
  6. if (!isPlainObject(data)) {
  7. data = {}
  8. process.env.NODE_ENV !== 'production' && warn(
  9. 'data functions should return an object:\n' +
  10. 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
  11. vm
  12. )
  13. }
  14. // proxy data on instance
  15. const keys = Object.keys(data)
  16. const props = vm.$options.props
  17. let i = keys.length
  18. while (i--) {
  19. if (props && hasOwn(props, keys[i])) {
  20. process.env.NODE_ENV !== 'production' && warn(
  21. `The data property "${keys[i]}" is already declared as a prop. ` +
  22. `Use prop default value instead.`,
  23. vm
  24. )
  25. } else {
  26. proxy(vm, keys[i]) // 目的是在實例對象上對數據進行代理,這樣我們就能通過 this.a 來訪問 data.a 了
  27. }
  28. }
  29. // observe data
  30. observe(data)
  31. data.__ob__ && data.__ob__.vmCount++
  32. }
上面 proxy 方法非常簡單,僅僅是在實例對象上設置與 data 屬性同名的訪問器屬性,然后使用 _data 做數據劫持,如下:
   
   
   
           
  1. function proxy (vm: Component, key: string) {
  2. if (!isReserved(key)) {
  3. Object.defineProperty(vm, key, { // vm是實例,key是data屬性上的屬性,
  4. configurable: true,
  5. enumerable: true,
  6. get: function proxyGetter () {
  7. return vm._data[key]
  8. },
  9. set: function proxySetter (val) {
  10. vm._data[key] = val
  11. }
  12. })
  13. }
  14. }
做完數據的代理,就正式進入響應系統:
   
   
   
           
  1. observe(data)
我們說過,數據響應系統主要包含三部分: Observer  、Dep、Watcher,

我們首先思考,我們應該如何觀察一個數據對象的變化?
vue.js和avalon.js 都是通過 Object.definedProperty() 方法來實現的, 下面我們主要來介紹一下這個方法為什么可以實現對對象屬性改變的監聽。
Object.defineProperty ( )有三個參數, 三個參數都需要,分別是對象,屬性,屬性的屬性
    
    
    
            
  1. var o = {};
  2. Object.definedProperty(o, 'a', {
  3. value: 'b'
  4. })
屬性的屬性有下面這些:
    
    
    
            
  1. configurable:true | false,
  2. enumerable:true | false,
  3. value:任意類型的值,
  4. writable:true | false
writable
該屬性的值是否可以修改;如果設置為false,則不能被修改,修改不會報錯,只是默默的不修改;
    
    
    
            
  1. var obj = {}
  2. //第一種情況:writable設置為false,不能重寫。
  3. Object.defineProperty(obj,"newKey",{
  4. value:"hello",
  5. writable:false
  6. });
  7. //更改newKey的值
  8. obj.newKey = "change value";
  9. console.log( obj.newKey ); //hello
  10. //第二種情況:writable設置為true,可以重寫
  11. Object.defineProperty(obj,"newKey",{
  12. value:"hello",
  13. writable:true
  14. });
  15. //更改newKey的值
  16. obj.newKey = "change value";
  17. console.log( obj.newKey ); //change value
enumerable
是否該屬性可以被 for……in 或者 Object.keys( ) 枚舉
    
    
    
            
  1. var obj = {}
  2. //第一種情況:enumerable設置為false,不能被枚舉。
  3. Object.defineProperty(obj,"newKey",{
  4. value:"hello",
  5. writable:false,
  6. enumerable:false
  7. });
  8. //枚舉對象的屬性
  9. for( var attr in obj ){
  10. console.log( attr );
  11. }
  12. //第二種情況:enumerable設置為true,可以被枚舉。
  13. Object.defineProperty(obj,"newKey",{
  14. value:"hello",
  15. writable:false,
  16. enumerable:true
  17. });
  18. //枚舉對象的屬性
  19. for( var attr in obj ){
  20. console.log( attr ); //newKey
  21. }

configurable
是否可以刪除目標屬性或是否可以再次修改屬性的特性(writable, configurable, enumerable)。設置為true可以被刪除或可以重新設置特性;設置為false,不能被可以被刪除或不可以重新設置特性。默認為false。
這個屬性起到兩個作用:
 1、  目標屬性是否可以使用delete刪除
 2、目標屬性是否可以再次設置特性
    
    
    
            
  1. //-----------------測試目標屬性是否能被刪除------------------------
  2. var obj = {}
  3. //第一種情況:configurable設置為false,不能被刪除。
  4. Object.defineProperty(obj,"newKey",{
  5. value:"hello",
  6. writable:false,
  7. enumerable:false,
  8. configurable:false
  9. });
  10. //刪除屬性
  11. delete obj.newKey; //可以用delete 關鍵字來刪除某一個對象上的屬性
  12. console.log( obj.newKey ); //hello
  13. //第二種情況:configurable設置為true,可以被刪除。
  14. Object.defineProperty(obj,"newKey",{
  15. value:"hello",
  16. writable:false,
  17. enumerable:false,
  18. configurable:true
  19. });
  20. //刪除屬性
  21. delete obj.newKey;
  22. console.log( obj.newKey ); //undefined
  23. //-----------------測試是否可以再次修改特性------------------------
  24. var obj = {}
  25. //第一種情況:configurable設置為false,不能再次修改特性。
  26. Object.defineProperty(obj,"newKey",{
  27. value:"hello",
  28. writable:false,
  29. enumerable:false,
  30. configurable:false
  31. });
  32. //重新修改特性
  33. Object.defineProperty(obj,"newKey",{
  34. value:"hello",
  35. writable:true,
  36. enumerable:true,
  37. configurable:true
  38. });
  39. console.log( obj.newKey ); //報錯:Uncaught TypeError: Cannot redefine property: newKey
  40. //第二種情況:configurable設置為true,可以再次修改特性。
  41. Object.defineProperty(obj,"newKey",{
  42. value:"hello",
  43. writable:false,
  44. enumerable:false,
  45. configurable:true
  46. });
  47. //重新修改特性
  48. Object.defineProperty(obj,"newKey",{
  49. value:"hello",
  50. writable:true,
  51. enumerable:true,
  52. configurable:true
  53. });
  54. console.log( obj.newKey ); //hello
一旦使用  Object.defineProperty  給對象添加屬性,那么如果不設置屬性的特性,那么configurable、enumerable、writable這些值都為默認的false

存取器描述 get set
不能  同時 設置訪問器 (get 和 set) 和 wriable 或 value,否則會錯,就是說想用(get 和 set),就不能用(wriable 或 value中的任何一個)
注意:get set是加在對象屬性上面的,不是對象上面的;賦值或者修改該對象屬性,會分別觸發get 和 set 方法;
正規用法:
    
    
    
            
  1. var o = {}; // 不能是O.name=" dudu "了
  2. var val = 'dudu'; // o 對象上的屬性是其他人家的一個變量
  3. Object.definedProperty(o,'name',{ // Object.definedProperty( ) 方法通過定set get 方法,強行給拉郎配
  4. get:function(){ return val }; //get: return val 把人家變量給返回了,就是人家的人了
  5. set;function(value){ val = value } //set: val = value 把人家變量賦值為傳進來的參數,就是人間人了
  6. })
實驗性代碼:
   
   
   
           
  1. var O = {};
  2. Object.definedProperty(o,"name",{
  3. set:function(){console.log('set')}; //在獲取對象該屬性的時候觸發,
  4. get:function(){console.log('get')}; // 在設置對象該屬性的時候觸發 , 並不會真正的設置;因為沖突了value,默認是falue
  5. })

所以,你看到這里,基本上就能夠明白,通過Object.defineProperty()來重寫對象的get, set 方法,就可以在對象屬性被訪問和修改的時候獲知 ,從而觸發響應的回調函數,但是同一個數據屬性,很可能有多個 watcher 來訂閱的 ,所觸發的回調函數可能有很多,不可能都寫在 get set 里面,我們更希望更通過這樣的方式:
   
   
   
           
  1. var data = {
  2. a: 1,
  3. b: {
  4. c: 2
  5. }
  6. }
  7. observer(data) // 在這里遍歷改寫了get,set
  8. new Watch('a', () => {
  9. alert(9)
  10. })
  11. new Watch('a', () => {
  12. alert(90)
  13. })
  14. new Watch('b.c', () => {
  15. alert(80)
  16. })
現在的問題是, Watch 構造函數要怎么寫?
在 Watch 構造函數里面,我們已經可以獲取到 data,當我們訪問的時候,就會觸發 data 的改寫的get 方法:
   
   
   
           
  1. class Watch {
  2. constructor (exp, fn) {
  3. // ……
  4. data[exp] // 觸發了data 身上的get 方法
  5. }
  6. }
當我們每實例化一個 Watch來訂閱data上的a屬性  , data.a 上的get 方法就會被觸發一次, data.a 就多了一個訂閱器。那么問題來了,這么多的訂閱器watcher,我們肯定希望放在一個數組上進行管理,同時我們還希望有,向數組中 push 新的訂閱器watcher的方法,  逐個觸發數組中各個watcher的方法等等。這樣,我們的data 上的每一個屬性,它都有一個數組來放訂閱器,都有相應的方法來操作這個數組。根據面向對象中的思想,我們可以把這個數組和操作數組的方法放進一個對象中, 這個對象就叫dep吧 :
   
   
   
           
  1. dep {
  2. subs: [watcher1,watcher2,watcher3], // subs 屬性是一個數組,用來維護眾多訂閱器
  3. addSubs: function(){ this.subs.push( …… ) },
  4. notify: function() {
  5. for(let i = 0; i< this.subs.length; i++){
  6. this.subs[i].fn()
  7. }
  8. }
  9. }
dep 對象我們希望用構造函數來生成,這樣會比較方便:
   
   
   
           
  1. class Dep {
  2. constructor () {
  3. this.subs = []
  4. }
  5. addSub () {
  6. this.subs.push(……)
  7. }
  8. notify () {
  9. for(let i = 0; i < this.subs.length; i++){
  10. this.subs[i].fn()
  11. }
  12. }
  13. }
接下來,我們要在每一個data 屬性上生成一個dep實例對象:
   
   
   
           
  1. function defineReactive (data, key, val) { // 這個函數就是用來重寫對象屬性的get set 方法
  2. observer(val) // 遞歸的調用從而遍歷
  3. let dep = new Dep() // 在這里實例化一個dep實例
  4. Object.defineProperty(data, key, {
  5. enumerable: true,
  6. configurable: true,
  7. get: function () {
  8. dep.addSub() //每當有訂閱者訂閱,我就新增一個
  9. return val
  10. },
  11. set: function (newVal) {
  12. if(val === newVal){
  13. return
  14. }
  15. observer(newVal)
  16. dep.notify() // 新增
  17. }
  18. })
  19. }
等等,在第8行,執行 dep.addSub , 我怎么知道是要push 進去哪個 watcher 呢? 我們需要改寫一下 watch 的構造函數:

   
   
   
           
  1. Dep.target = null //類似於全局變量的一個東西,用來放 這次實例化的watcher
  2. function pushTarget(watch){
  3. Dep.target = watch
  4. }
  5. class Watch {
  6. constructor (exp, fn) {
  7. this.exp = exp
  8. this.fn = fn
  9. pushTarget(this) // 讓Dep.target賦值為本次實例化的實例
  10. data[exp] //緊接着就觸發get 方法
  11. }
  12. }
被觸發的get 方法在下面:
   
   
   
           
  1. get: function () {
  2. dep.addSub() //好吧,我又被觸發了一次,
  3. return val
  4. },
dep.addSub() 方法的廬山真面目:
   
   
   
           
  1. class Dep {
  2. constructor () {
  3. this.subs = []
  4. }
  5. addSub () {
  6. this.subs.push(Dep.target)
  7. }
  8. notify () {
  9. for(let i = 0; i < this.subs.length; i++){
  10. this.subs[i].fn()
  11. }
  12. }
  13. }
















免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM