Skip to content

Latest commit

 

History

History
74 lines (66 loc) · 1.75 KB

01.md

File metadata and controls

74 lines (66 loc) · 1.75 KB

原理图

构造Vue

function Vue (opts) {
  // 一些检查this指向代码
  this._init(opts)
}

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export function initState (vm: Component) {
  vm._watchers = []
  const opts = vm.$options
  if (opts.props) initProps(vm, opts.props)
  if (opts.methods) initMethods(vm, opts.methods)
  if (opts.data) {
    initData(vm)
  } else {
    observe(vm._data = {}, true /* asRootData */)
  }
  if (opts.computed) initComputed(vm, opts.computed)
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch)
  }
}

初始化顺序 props -> methods -> data -> computed -> watch

stateMixin

// 做 data 属性和 props 属性的代理
const dataDef = {}
const propsDef = {}

// 定义三个方法
Vue.prototype.$set = set
Vue.prototype.$delete = del
Vue.prototype.$watch = function() {}

eventsMixin

// 定义事件相关
Vue.prototype.$on = function() {}
Vue.prototype.$once = function() {}
Vue.prototype.$off = function() {}
Vue.prototype.$emit = function() {}

lifecycleMixin

// 注册和生命周期相关的API
Vue.prototype._update = function() {}
Vue.prototype.$foreceUpdate = function() {}
Vue.prototype.$destroy = function() {}

renderMixin

// 一些列 render 相关方法

Vue.prototype.$nextTick = function() {}
Vue.prototype._render = function() {}

小结

  1. 利用类似装饰者模式修改 Vue 的原型,优点在于使得逻辑清晰,每一个 Mixin 只负责自己的部分
  2. 主要给 Vue 原型添加 API 方法,以及添加 Vue 的静态属性
  3. 目前为止都是纯 JS 层面操作,没有涉及浏览器相关的 API