vue源码心得--Vue对象生成方式(混入)

2020-11-12  本文已影响0人  某时橙

part1.源码部分

//位置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

这里的Vue对象实际上就是通过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)
}

为何 Vue 不用 ES6 的 Class 去实现呢?我们往后看这里有很多 xxxMixin 的函数调用,并把 Vue 当参数传入,它们的功能都是给 Vue 的 prototype 上扩展一些方法(这里具体的细节会在之后的文章介绍,这里不展开),Vue 按功能把这些扩展分散到多个模块中去实现,而不是在一个模块里实现所有,这种方式是用 Class 难以实现的。这么做的好处是非常方便代码的维护和管理。

part2.模块实现

function Warlock(){
 this._init({
   name:'warlock',
   year:'21',
 })
}
function initObj(obj){
  obj.prototype._init=function(option){
    this.name=option.name;
    this.year=option.year;
  }
}
initObj(Warlock)
let obj=new Warlock();

warlock对象的init的方法就通过下面的initObj“混入”,
现在打开F12,复制上段代码并复制控制台之,运行,看看obj的结果


obj

这就是vue的通过混入的模块管理方式,非常值得我们学习!

上一篇 下一篇

猜你喜欢

热点阅读