【Vue】Vue源码阅读笔记(1)

2 篇文章 0 订阅

本文主要记录了VUE源码中的三部分:

  1. VUE初始化流程
  2. VUE中响应式实现
  3. VUE对数组做特殊处理

初始化流程

入口
src\platforms\web\entry-runtime-with-compiler.js

扩展$mount

  const options = this.$options
  // resolve template/el and convert to render function
  //判断是否有render函数,没有的话就编译template。
  //render优先级高于template
  if (!options.render) {
    let template = options.template
    //如果template存在,解析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) {
        //如果el存在,则获取外部的所有HTML
      template = getOuterHTML(el)
    }
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }
      //通过编译函数,把template编译成render函数
      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')
      }
    }
  }

WEB运行时代码
src\platforms\web\runtime\index.js

// 安装平台补丁功能
//如果是浏览器环境,那么开始载入__patch__,用来给虚拟dom打补丁生成真实DOM的
Vue.prototype.__patch__ = inBrowser ? patch : noop

// 实现$mount 挂载全局$mount函数,打包挂载到el上
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

全局API定义
src\core\index.js

//初始化全局API
initGlobalAPI(Vue)

全局API实现
src\core\global-api\index.js
initGlobalAPI (Vue: GlobalAPI) {

Vue.set = set
  Vue.delete = del
  Vue.nextTick = nextTick

  initUse(Vue) // 实现Vue.use函数
  initMixin(Vue) // 实现Vue.mixin函数
  initExtend(Vue) // 实现Vue.extend函数
  initAssetRegisters(Vue) // 注册实现Vue.component/directive/filter
}

Vue构造函数定义
src\core\instance\index.js

//VUE构造函数
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)
}
//初始化_init函数
initMixin(Vue)
//定义$set $delete $watch $props $data
stateMixin(Vue)
//定义$on $once $emit $off
eventsMixin(Vue)
//定义$forceUpdate、$destory
lifecycleMixin(Vue)
//定义nextTick 和 _render
renderMixin(Vue)

initMixin函数
调用beforeCreate函数
调用created函数

beforeCreated之前执行了initLifecycle、initEvents、initRender

// 设置$parent,$root,$children等组件关系属性
initLifecycle(vm)
// 监听附加在组件上的事件
initEvents(vm)
// 初始化组件插槽、声明createElement方法  
initRender(vm)
// 调用beforeCreate钩子
callHook(vm, 'beforeCreate')
// 初始化注入数据
initInjections(vm) // resolve injections before data/props
// 初始化组件data,methods,computed,watch
initState(vm)
// 为后代提供数据
initProvide(vm) // resolve provide after data/props
// 调用created钩子
callHook(vm, 'created')

if (vm.$options.el) {
  vm.$mount(vm.$options.el)
}

stateMixin函数
watch中如果有immediate属性,则watch立即执行

  //添加响应式set到data和props中
  Object.defineProperty(Vue.prototype, '$data', dataDef)
  Object.defineProperty(Vue.prototype, '$props', propsDef)
  //初始化全局$set和$delete函数
  Vue.prototype.$set = set
  Vue.prototype.$delete = del
  //初始化全局$watch
  Vue.prototype.$watch = function (
    expOrFn: string | Function,
    cb: any,
    options?: Object
  ): Function {
    const vm: Component = this
    if (isPlainObject(cb)) {
      return createWatcher(vm, expOrFn, cb, options)
    }
    options = options || {}
    options.user = true
    const watcher = new Watcher(vm, expOrFn, cb, options)
***  //watch中如果有immediate属性,则watch立即执行
    if (options.immediate) {
      try {
        cb.call(vm, watcher.value)
      } catch (error) {
        handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)
      }
    }
    return function unwatchFn () {
      watcher.teardown()
    }
  }

lifecycleMixin(Vue)函数
_update中__patch__方法返回的是真实dom

Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
    const vm: Component = this
    const prevEl = vm.$el
    const prevVnode = vm._vnode
    const restoreActiveInstance = setActiveInstance(vm)
    vm._vnode = vnode
    // Vue.prototype.__patch__ is injected in entry points
    // based on the rendering backend used.
    if (!prevVnode) {
      // 初次更新
     **** //__patch__方法返回的是真实dom可以从这里看出
      vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
    } else {
      // 更新
      vm.$el = vm.__patch__(prevVnode, vnode)
    }
    restoreActiveInstance()
    // 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.
  }

forceUpdate
实际是调用watcher的更新函数
vm._watcher.update()

destory
调用beforeDestory钩子函数
在父类中删除子类实例
注销watcher
删除渲染节点

Vue.prototype.$destroy = function () {
    const vm: Component = this
    if (vm._isBeingDestroyed) {
      return
    }
    //调用beforeDestory生命钩子
    callHook(vm, 'beforeDestroy')
    vm._isBeingDestroyed = true
    // remove self from parent
    const parent = vm.$parent
    if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
        //在父类中删除当前子类
      remove(parent.$children, vm)
    }
    //注销watcher
    if (vm._watcher) {     
      vm._watcher.teardown()
    }
    let i = vm._watchers.length
    while (i--) {
      vm._watchers[i].teardown()
    }
    // remove reference from data ob
    // frozen object may not have observer.
    if (vm._data.__ob__) {
      vm._data.__ob__.vmCount--
    }
    // call the last hook...
    vm._isDestroyed = true
    // 销毁渲染树上的节点
    vm.__patch__(vm._vnode, null)
    // 调用destory钩子函数
    callHook(vm, 'destroyed')
    // turn off all instance listeners.
    vm.$off()
    // 删除Vue挂载
    if (vm.$el) {
      vm.$el.__vue__ = null
    }
    // 删除node节点
    if (vm.$vnode) {
      vm.$vnode.parent = null
    }
  }

renderMixin函数
_render函数
获取当前实例的options属性里的render
然后调用render方法,传入initMixin中initRender定义的creatElement方法。
这就是为什么我们写render的时候要传入一个参数h,而h就是creatElement

render(h){
    return h('div',{attr:{id:'div'}})
}

Vue.prototype._render = function (): VNode {
    const vm: Component = this
    const { render, _parentVnode } = vm.$options

    if (_parentVnode) {
      vm.$scopedSlots = normalizeScopedSlots(
        _parentVnode.data.scopedSlots,
        vm.$slots,
        vm.$scopedSlots
      )
    }

    // 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 {
      // There's no need to maintain a stack because all render fns are called
      // separately from one another. Nested component's render fns are called
      // when parent component is patched.
      currentRenderingInstance = vm
      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' && 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
      }
    } finally {
      currentRenderingInstance = null
    }
    // if the returned array contains only a single node, allow it
    if (Array.isArray(vnode) && vnode.length === 1) {
      vnode = vnode[0]
    }
    // 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
  }
}

响应式原理

src\core\instance\state.js
initData函数
判断data是类型,如果是函数则返回执行结果
然后判断data是不是对象
返回一个observe方法

function initData (vm: Component) {
  let data = vm.$options.data
  //判断data是类型,如果是函数则返回执行结果
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
    //然后判断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
  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 */)
}

observe方法
src\core\observer\index.js

判断是否已经有observer,有的话直接返回observer对象,没有的话就新建一个observer对象
export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

Observer对象根据数据类型执行对应的响应化操作
附加到每个被观察对象的观察者类对象。
一旦附加,观察者将转换目标将对象的属性键转换为getter/setter
收集依赖项并分派更新。

一个观察者对象,添加目标对象
并且为对象的属性添加getter和setter事件的监听
并做依赖收集 this.dep = new Dep()
对数组和对象做不同的响应和操作

export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that have this object as root $data

  constructor (value: any) {
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
    def(value, '__ob__', this)
    //对数组做响应化
    if (Array.isArray(value)) {
      if (hasProto) {
        protoAugment(value, arrayMethods)
      } else {
        copyAugment(value, arrayMethods, arrayKeys)
      }
      this.observeArray(value)
    } else {
        //对对象做响应化
      this.walk(value)
    }
  }

对数组做响应化的方法
遍历数组每一项,为每一项添加observe,把数组每一项都变成响应式

observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }

对对象做响应的方法
遍历对象key,执行响应式方法

  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }

Vue响应式方法defineReactive

defifineReactive定义对象属性的getter/setter,getter负责添加依赖,setter负责通知更新
一个key一个Dep实例

export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  const dep = new Dep()
  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }
  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }
  let childOb = !shallow && observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      //getter被调用时若存在依赖则追加
      if (Dep.target) {
        dep.depend()
        if (childOb) {
            // 若存在子observer,则依赖也追加到子ob
          childOb.dep.depend()
          if (Array.isArray(value)) {
              // 数组需特殊处理
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      // #7981: for accessor properties without setter
      if (getter && !setter) return
      if (setter) {
        setter.call(obj, newVal)
      } else {
          //更新值
        val = newVal
      }
      //递归执行子对象响应化
      childOb = !shallow && observe(newVal)
      //通知组件更新
      dep.notify()
    }
  })
}

扩展数组响应化的7个常用方法

// 数组原型
const arrayProto = Array.prototype
// 修改后的原型
export const arrayMethods = Object.create(arrayProto)
// 七个待修改方法
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
/**
* 拦截这些方法,额外发送变更通知
*/
methodsToPatch.forEach(function (method) {
    // 原始数组方法
    const original = arrayProto[method]
    // 修改这些方法的descriptor
    def(arrayMethods, method, function mutator (...args) {
    // 原始操作
    const result = original.apply(this, args)
    // 获取ob实例用于发送通知
    const ob = this.__ob__
    // 三个能新增元素的方法特殊处理
    let inserted
    switch (method) {
    case 'push':
    case 'unshift':
    inserted = args
    break
    case 'splice':
    inserted = args.slice(2)开课吧web全栈架构师
    break
    }
    // 若有新增则做响应处理
    if (inserted) ob.observeArray(inserted)
    // 通知更新
    ob.dep.notify()
    return result
    })
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值