[Vue源码分析]:再探Vue世界_new Vue()

前言

在使用Vue2框架的时候,在main.js中使用的new Vue()来实现我们写的组件渲染到真实的DOM中,那么new Vue 都做了什么呢?为什么不是用一个function 直接返回呢,为什么要用new Vue创建一个实例呢

new Vue 做了什么

查找Vue源码得知,Vue类的定义是在源码的src/core/instance/index.js 中,如下:

js 复制代码
import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'

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)
}

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue

这个方法中重要的代码就一行

js 复制代码
 this._init(options)

我们在函数中调用 this 的方法,如果本身没有定义,那么根据原型链规则向上寻找,Vue.prototype.init的定义源码在src/core/instance/init.js

js 复制代码
/* @flow */

import config from '../config'
import { initProxy } from './proxy'
import { initState } from './state'
import { initRender } from './render'
import { initEvents } from './events'
import { mark, measure } from '../util/perf'
import { initLifecycle, callHook } from './lifecycle'
import { initProvide, initInjections } from './inject'
import { extend, mergeOptions, formatComponentName } from '../util/index'

let uid = 0

export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
    debugger
    const vm: Component = this
    // a uid
    vm._uid = uid++

    let startTag, endTag
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag)
    }

    // a flag to avoid this being observed
    vm._isVue = true
    // merge options
    if (options && options._isComponent) {
      // optimize internal component instantiation
      // since dynamic options merging is pretty slow, and none of the
      // internal component options needs special treatment.
      initInternalComponent(vm, options)
    } else {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    // expose real self
    vm._self = vm
    initLifecycle(vm)
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')
    initInjections(vm) // resolve injections before data/props
    initState(vm)
    initProvide(vm) // resolve provide after data/props
    callHook(vm, 'created')

    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      vm._name = formatComponentName(vm, false)
      mark(endTag)
      measure(`vue ${vm._name} init`, startTag, endTag)
    }

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

export function initInternalComponent (vm: Component, options: InternalComponentOptions) {
  const opts = vm.$options = Object.create(vm.constructor.options)
  // doing this because it's faster than dynamic enumeration.
  const parentVnode = options._parentVnode
  opts.parent = options.parent
  opts._parentVnode = parentVnode

  const vnodeComponentOptions = parentVnode.componentOptions
  opts.propsData = vnodeComponentOptions.propsData
  opts._parentListeners = vnodeComponentOptions.listeners
  opts._renderChildren = vnodeComponentOptions.children
  opts._componentTag = vnodeComponentOptions.tag

  if (options.render) {
    opts.render = options.render
    opts.staticRenderFns = options.staticRenderFns
  }
}

export function resolveConstructorOptions (Ctor: Class<Component>) {
  let options = Ctor.options
  if (Ctor.super) {
    const superOptions = resolveConstructorOptions(Ctor.super)
    const cachedSuperOptions = Ctor.superOptions
    if (superOptions !== cachedSuperOptions) {
      // super option changed,
      // need to resolve new options.
      Ctor.superOptions = superOptions
      // check if there are any late-modified/attached options (#4976)
      const modifiedOptions = resolveModifiedOptions(Ctor)
      // update base extend options
      if (modifiedOptions) {
        extend(Ctor.extendOptions, modifiedOptions)
      }
      options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
      if (options.name) {
        options.components[options.name] = Ctor
      }
    }
  }
  return options
}

function resolveModifiedOptions (Ctor: Class<Component>): ?Object {
  let modified
  const latest = Ctor.options
  const sealed = Ctor.sealedOptions
  for (const key in latest) {
    if (latest[key] !== sealed[key]) {
      if (!modified) modified = {}
      modified[key] = latest[key]
    }
  }
  return modified
}

根据源码可以看到,initMixin 方法,只在 Vue 的原型上增加了一个 init 方法,所以new Vue 所处理的工作就是 init 方法内部的功能 接下来我们来看 init 方法内部的实现

js 复制代码
    vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )

合并属性Options。子会覆盖父的属性

其中 resolveConstructorOptions(vm.constructor),这个属于Vue.extend 继承功能传入的属性

接下来就是一些初始化函数,初始化我们Options传入的属性,后面详细分析每个方式的实现

js 复制代码
initLifecycle(vm)       // 初始化生命周期
initEvents(vm)        // 初始化事件
initRender(vm)         // 初始化渲染
callHook(vm, 'beforeCreate')  // 调用生命周期钩子函数
initInjections(vm)   //初始化injections
initState(vm)    // 初始化props,methods,data,computed,watch
initProvide(vm) // 初始化 provide
callHook(vm, 'created')  // 调用生命周期钩子函数

挂载到页面上

js 复制代码
  if (vm.$options.el) {
      vm.$mount(vm.$options.el)
  }

以上就是new Vue 时处理的功能,内部详细的功能后面会更新文章做详细的讲解

什么要使用构造函数的方式

为什么Vue不是直接使用函数的形式执行呢,比如

js 复制代码
dom=Vue(options)

我们知道在使用VueAPi时候我们是直接 this 调用的 ,如果直接Vue()执行了,那么他内部的 this 就指向了 调用事的调用者。

构造函数的好处使用简单,我们在使用的时候在全局调用 this. <math xmlns="http://www.w3.org/1998/Math/MathML"> a l e r t ( ) 方法的时候,其实内部我们就本身给 V u e . p r o t o t y p e , alert() 方法的时候,其实内部我们就本身给Vue.prototype, </math>alert()方法的时候,其实内部我们就本身给Vue.prototype,alert 增加了方法,但是缺点就是给Vue.prototype上增加了很多方法,导致Vue本身很笨重,多人开发的时候可能还会出现命名冲突。 所以Vue3支持了函数式的方式,内部封装使用

相关推荐
用户51681661458415 小时前
Vue Router 路由懒加载引发的生产页面白屏问题
vue.js·vue-router
前端缘梦5 小时前
Vue Keep-Alive 组件详解:优化性能与保留组件状态的终极指南
前端·vue.js·面试
Simon_He6 小时前
这次来点狠的:用 Vue 3 把 AI 的“碎片 Markdown”渲染得又快又稳(Monaco 实时更新 + Mermaid 渐进绘图)
前端·vue.js·markdown
王同学QaQ11 小时前
Vue3对接UE,通过MQTT完成通讯
javascript·vue.js
华仔啊11 小时前
基于 RuoYi-Vue 轻松实现单用户登录功能,亲测有效
java·vue.js·后端
艾小码12 小时前
告别Vue混入的坑!Composition API让我效率翻倍的3个秘密
前端·javascript·vue.js
Gracemark1 天前
高德地图-地图选择经纬度问题【使用输入提示-使用Autocomplete进行联想输入】(复盘)
vue.js
天下无贼1 天前
【手写组件】 Vue3 + Uniapp 手写一个高颜值日历组件(含跨月补全+今日高亮+选中状态)
前端·vue.js
洋葱头_1 天前
vue3项目不支持低版本的android,如何做兼容
前端·vue.js
奔跑的蜗牛ing1 天前
Vue3 + Element Plus 输入框省略号插件:零侵入式全局解决方案
vue.js·typescript·前端工程化