[Vue源码分析]:再探Vue世界_new Vue()
前言
在使用Vue2框架的时候,在main.js中使用的new Vue()来实现我们写的组件渲染到真实的DOM中,那么new Vue 都做了什么呢?为什么不是用一个function 直接返回呢,为什么要用new Vue创建一个实例呢
new Vue 做了什么
查找Vue源码得知,Vue
类的定义是在源码的src/core/instance/index.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
这个方法中重要的代码就一行
this._init(options)
我们在函数中调用 this 的方法,如果本身没有定义,那么根据原型链规则向上寻找,Vue.prototype.init的定义源码在src/core/instance/init.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
方法内部的实现
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
合并属性Options。子会覆盖父的属性
其中 resolveConstructorOptions(vm.constructor),
这个属于Vue.extend 继承功能传入的属性
接下来就是一些初始化函数,初始化我们Options传入的属性,后面详细分析每个方式的实现
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') // 调用生命周期钩子函数
挂载到页面上
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
以上就是new Vue 时处理的功能,内部详细的功能后面会更新文章做详细的讲解
什么要使用构造函数的方式
为什么Vue不是直接使用函数的形式执行呢,比如
dom=Vue(options)
我们知道在使用VueAPi时候我们是直接 this 调用的 ,如果直接Vue()执行了,那么他内部的 this 就指向了 调用事的调用者。
构造函数的好处使用简单,我们在使用的时候在全局调用 this.alert()方法的时候,其实内部我们就本身给Vue.prototype,alert() 方法的时候,其实内部我们就本身给Vue.prototype,alert()方法的时候,其实内部我们就本身给Vue.prototype,alert 增加了方法,但是缺点就是给Vue.prototype上增加了很多方法,导致Vue本身很笨重,多人开发的时候可能还会出现命名冲突。
所以Vue3
支持了函数式的方式,内部封装使用
转载自:https://juejin.cn/post/7356906581780611113