Vue.js 的原始碼全都在 src 資料夾下,src 資料夾結構如下
src/        
├── compiler/        # 編譯相關,把 template 編譯為 render function
├── core/            # 核心程式碼
├── platforms/       # 不同平台的支持
├── server/          # server 端渲染
├── sfc/             # .vue 文件的解析,用於 vue-template-compiler
├── shared/          # 通用程式碼
我們從兩隻檔案看 new Vue 做了什麼
src/core/instance/index.js
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 只能用 new 關鍵字初始化this._init 方法,此方法定義在下面 2 中。Vue 其實是一個 class( JS 中用 function 實現 class )src/core/instance/init.js
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 初始化最主要做幾件事,其實從執行哪些 function 可以看出來
initLifecycle(vm) 初始化生命週期initEvents(vm) 初始化事件中心initRender(vm) 初始化渲染callHook(vm, 'beforeCreate') 調用生命週期 hook,beforeCreate 方法initState(vm) 初始化 data、props、computed、watcher 等等callHook(vm, 'created') 調用生命週期 hook,created 方法初始化最後若有檢查到 el 屬性,則調用 vm.$mount 方法把vm 掛載到給定的 DOM 元素上
感謝分享
補充 new Vue() 是 Vue 2 的語法,
Vue 3 用 Vue.createApp() 取代 new Vue()
https://book.vue.tw/appendix/migration.html#%E5%85%83%E4%BB%B6%E5%AF%A6%E9%AB%94%E5%BB%BA%E7%AB%8B
Vue 2 support will end on Dec 31, 2023. Learn more about Vue 2 Extended LTS.
The Benefits of the New Vue 3 App Initialization Code