探索Vue.js底层源码——Vue构造函数

Vue构造函数

在开发当中,我们通过会通过 new Vue 创建一个 Vue 实例。而在 Vue 源码中,Vue的构造函数定义在 /src/core/index.js 中。

	function Vue (options) {
	  // 如果开发环境不是生产环境且该调用该function的不是Vue的实例
	  if (process.env.NODE_ENV !== 'production' &&
	    !(this instanceof Vue)
	  ) {
	    // 提示Vue是一个构造方法并且必须通过new关键字调用
	    warn('Vue is a constructor and should be called with the `new` keyword')
	  }
	  // 初始化参数
	  this._init(options)
	}

在Vue的构造函数中,最终会执行_init()方法,而_init()方法定义在 init.js 中。而在 _init() 方法中,针对 options._isComponent 是否为真,即是否是组件分别进行了不同的初始化。
一、如果为真,即是组件,则执行initInternalComponent()方法

	initInternalComponent(vm, options)

二、如果不为真,即不是组件,则合并选项,并赋值给当前实例的 $options

	vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )

接下来都是进行相同的函数

	//初始化Proxy 
	initProxy(vm)
	//进行各种初始化函数
	initLyfecycle(vm)
	initEvents(vm)
	initRender(vm)
	callHook(vm, 'beforeCreate')
	initInjections(vm)
	initState(vm)
	intiProvide(vm)
	callHook(vm, 'create')

最后判断 vm 实例上的 $options.el 属性上是否存在,存在则调用 $mount() 方法 挂载实例。而 $mount() 的编译版本则定义在 src/platform/web/entry-runtime-compiler.js 中。而 $mount 方法中会根据options.render函数是否存在,分别进行不同的函数调用。
一、options.render存在,直接调用原先定义的原型方法 $mount

	return mount.call(this, el, hydrating)

二、options.render不存在,根据optinos.template是否存在,又分别进行不同的函数调用。最终获取包含这个el的相应的HTML代码,对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

最后仍然是调用原先定义的原型方法 $mount 方法,而这个原型方法定义在 src/platform/web/runtime/index.js 中。

	Vue.prototype.$mount = function (
	  el?: string | Element,
	  hydrating?: boolean
	): Component {
	  // 判断el是否存在以及window对象 存在则查询到该DOM
	  el = el && inBrowser ? query(el) : undefined
	  return mountComponent(this, el, hydrating)
	}

在 $mount 方法中会先获取el对于的真实 DOM 对象,然后将当前 Vue 实例和 el(真实DOM) 作为参数传入montComponent 方法中。而 mountComponent 方法则定义在 src/core/instance/lifecycle 中。

	export function mountComponent (
	  vm: Component,  // vm实例
	  el: ?Element, // 需要挂载的元素
	  hydrating?: boolean
	): Component {
	  // 将el缓存至vm.$el中
	  vm.$el = el
	  // 判断当前实例vm的$options是否存在render函数
	  if (!vm.$options.render) {
	    // 不存在
	    // 在vm实例上的$options上扩展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
	        )
	      }
	    }
	  }
	  callHook(vm, 'beforeMount')
	
	  let updateComponent
	  /* istanbul ignore if */
	  // config.performance 或 mark是和性能相关的参数
	  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 = () => {
	      // hydrating是和服务端渲染相关的参数  默认为false
	      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
	  // 初始化观察者模式
	  // 传入参数vm实例 updateComponnet noop空函数 对象 boolean
	  new Watcher(vm, updateComponent, noop, {
	    before () {
	      if (vm._isMounted && !vm._isDestroyed) {
	        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
	  if (vm.$vnode == null) {
	    vm._isMounted = true
	    callHook(vm, 'mounted')
	  }
	  return vm
	}

mountComponent 方法的作用是先实例化一个渲染 Watcher,在它的回调函数中会调用 updateComponent 方法·,在此方法中中调用 vm_render 方法先生成虚拟 DOM,最终调用 vm_update 更新 DOM。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值