viaje de vue Fuente -1- nueva Vue () hecho algo?

directorio de origen:

     

 

Fuente: 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

A partir de esta pieza de código se puede ver, Vue es una función ordinaria (constructor), pasando un parámetro de opciones, que son parte de la información de configuración de usuario entrante, la clave  this._init (opciones) Este método, que Vue es inicializar algunas configuraciones, y luego encontrar este _init método (), 

src / core / instancia / línea Init.js: 15

export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
    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)
    }
  }
}

vue función se puede ver en un prototipo extiende la _init ()  método, el código aquí mirar estos bordes se puede ver, este método es inicializar alguna configuración básica interna Vue, y finalmente en el montaje especificado dom

Aquí se puede ver la inicialización

gancho de ciclo de vida del componente, eventos personalizados, renderizado, y el estado de estado

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

vistazo a continuación,

src / Core /instance/state.js  (el código demasiado en la pantalla),

Aquí el Posteriormente inicial,

datos de los datos, los atributos de los apoyos, la observación atributos del reloj, computarizada, métodos y métodos de cálculo, y similares es mixta

resumen:

nuevo Vue () se produjo:

Desde el Vue, es inicializar alguna configuración interna Vue,

Pues bien, desde una nueva perspectiva, es decir,

Implementación de una nueva simulación

function Animal(name) {
  this.name = name
  return {
    name: 'liSi'
  }
}
Animal.prototype.say = function() {
  console.log('Miao')
}
function myNew() {
  // 取出第一个参数, 剩余的arguments 就是其他的参数
  let constructor = [].shift.call(arguments)
  // 不要使用 Object.create(null) 创建的对象, 因为没有原型链 __proto__
  let obj = {} // 返回的结果
  obj.__proto__ = constructor.prototype // 继承原型上的方法
  let result = constructor.apply(obj, arguments) // 改变this 指向 ,把剩余的参数传给它
  // 判断如果是一个 引用类型, 则直接返回这个引用类型的数据
  // 即判断是不是 Object 的实例
  return result instanceof Object ? result : obj
}
let animal = myNew(Animal, '猫')
console.log(animal) // {name: "liSi"}

 

Publicado 63 artículos originales · ganado elogios 100 · vistas 310 000 +

Supongo que te gusta

Origin blog.csdn.net/qq_36407748/article/details/105138691
Recomendado
Clasificación