vue2源码告诉你的那些事儿——vue初始化

如何找到vue的构造函数

打开源码中的package.json,找到你研究的版本所对应的TARGET,代码如下:

"dev": "rollup -w -c scripts/config.js --sourcemap --environment TARGET:web-full-dev",

 

在scripts/config.js中搜索web-full-dev,找到对应的入口文件。

'web-full-dev': {
    entry: resolve('web/entry-runtime-with-compiler.js'),
    dest: resolve('dist/vue.js'),
    format: 'umd',
    env: 'development',
    alias: { he: './entity-decoder' },
    banner
  },

 

在src/platforms/web/entry-runtime-with-compiler.js中,扩展了$mount方法。

首先判断是否将节点挂载到body和html上

if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }
// 扩展默认$mount方法:能够编译template或el指定的模板
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean )
  : Component {
  // 获取选项
  const options = this.$options
  // 不存在render选项,则将template/el的设置转换为render函数
  if (!options.render) {
    let template = options.template
    if (template) {
      // 解析template选项
    } else if (el) {
      // 否则解析el选项
      template = getOuterHTML(el)
    }if (template) {
      // 编译得到render函数
      const { render, staticRenderFns } = compileToFunctions(template, {..}, this)
      options.render = render
    }
  } 
  // 执行默认$mount函数 return mount.call(this, el, hydrating) 
}

 

在src\platforms\web\runtime\index.js中,找到$mount方法,关键就是mountComponent
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

 

在mountComponent中,定义了更新函数,创建了一个watcher,它会执行一次更新函数,完成挂载。

updateComponent = () => { 
  vm._update(vm._render(), hydrating) 
}
new Watcher(vm, updateComponent, noop, {
  before () { 
    if (vm._isMounted && !vm._isDestroyed) { 
      callHook(vm, 'beforeUpdate') 
    } 
  } 
  }, true /* isRenderWatcher */)

 

在src/core/index.js中,初始化了全局API

Vue.set
Vue.delete 
Vue.nextTick
initUse(Vue)
initMixin(Vue)
initExtend(Vue)

 

在src/core/instance/index.js中,找到了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)
}

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

 

初始化都做了什么(待续)

 

posted @ 2020-04-12 15:53  自由与未来  阅读(170)  评论(0)    收藏  举报