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
Vue 没有用 ES6 的 Class 去实现,后面的initMixin(Vue) 等函数调用, 是把构造函数当做参数传入,然后在构造函数的原型上添加相关的方法,例如在initMixin中:
export function initMixin (Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
...
Vue按功能把这些扩展分散到多个模块中去实现,而不是在一个模块里实现所有,这种方式是用 Class 难以实现的。这么做的好处是非常方便代码的维护和管理,这种编程技巧很值得学习.
版权声明:
作者:东明兄
链接:https://blog.crazyming.com/note/1314/
来源:CrazyMing
文章版权归作者所有,未经允许请勿转载。


共有 0 条评论