vue源碼分析1-new Vue做了哪些操作

首先我們可以看到vue的源碼在github上有,大家可以克隆下來(lái)。 git地址 我們主要看src下的內(nèi)容。

image

1.現(xiàn)在我們來(lái)分析下 new Vue都做了哪些操作

var app = new Vue({
  el: '#app',
  mounted:{
      console.log(this.message)
  }
  data: {
    message: 'Hello Vue!'
  }
})

我們都知道new關(guān)鍵字在js中代表實(shí)例化一個(gè)對(duì)象,而vue實(shí)際上是一個(gè)類,類在js中是用Function來(lái)實(shí)現(xiàn)的,在源碼的

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'
// 聲明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類傳入各種初始化方法
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export default Vue

可以看到vue只能通過(guò)new關(guān)鍵字初始化,然后會(huì)調(diào)用this._init方法,同時(shí)把options參數(shù)傳入,_init是vue原型上的一個(gè)方法。那么接下來(lái)我們看下_init方法做了些什么。在initMixin中定義了_init方法。

  • src/core/instance/init.js中

Vue.prototype._init = function (options?: Object) {
    // this指向Vue的實(shí)例,所以這里是將Vue的實(shí)例緩存給vm變量
    const vm: Component = this
    //定義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   合并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) // 初始化state
    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)// 調(diào)用vm上的$mount方法去掛載
    }
  }

Vue 初始化主要就干了幾件事情,合并配置,初始化生命周期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等等。

當(dāng)我們?cè)赾hrome的console中可以看到打印出來(lái)的data.message的值。試想一下,為什么我們能夠輸出這個(gè)值呢?帶著這個(gè)問(wèn)題我們來(lái)看看initState

  • src/core/instance/state.js

export function initState (vm: Component) {
  vm._watchers = []
  //如果定義了options,則始初化options,
  const opts = vm.$options
  if (opts.props) initProps(vm, opts.props) //如果有props,則初始化initProps
  if (opts.methods) initMethods(vm, opts.methods)//如果有methods,則初始化initMethods
  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)
  }
}

我們具體看下初始化的initData.

function initData (vm: Component) {
  let data = vm.$options.data
  data = vm._data = typeof data === 'function'    //判斷data類型是否是一個(gè)function,并賦值給vm._data
    ? getData(data, vm)
    : data || {}
  if (!isPlainObject(data)) {  //判斷data是否是一個(gè)對(duì)象,如果不是,報(bào)一堆警告
    data = {}
    process.env.NODE_ENV !== 'production' && warn(
      'data functions should return an object:\n' +
      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
      vm
    )
  }
  // 拿到對(duì)象的keys,props,methods
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    if (process.env.NODE_ENV !== 'production') {
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    if (props && hasOwn(props, key)) {
      process.env.NODE_ENV !== 'production' && warn(
        `The data property "${key}" is already declared as a prop. ` +
        `Use prop default value instead.`,
        vm
      )
    } else if (!isReserved(key)) {
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  observe(data, true /* asRootData */)
}

當(dāng)我們的data是一個(gè)函數(shù)的時(shí)候,會(huì)去調(diào)用getData,然后在getData中返回data。

export function getData (data: Function, vm: Component): any {
  pushTarget()
  try {
    return data.call(vm, vm)
  } catch (e) {
    handleError(e, vm, `data()`)
    return {}
  } finally {
    popTarget()
  }
}

我們拿到對(duì)象的keys,props,methods時(shí)進(jìn)行一個(gè)循環(huán)判斷,我們?cè)赿ata上定義的屬性值有沒(méi)有在props中也被定義,如果有,則報(bào)警告,這是因?yàn)槲覀兌x的所有值最終都會(huì)綁定到vm上,通過(guò)proxy實(shí)現(xiàn),調(diào)用proxy,將_data作為sourceKey傳入。

export function proxy (target: Object, sourceKey: string, key: string) {
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]  //vm._data.key會(huì)訪問(wèn)這
  }
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

通過(guò)這個(gè)對(duì)象定義了一個(gè)get,set。當(dāng)我們?cè)L問(wèn)this.message時(shí)也就是訪問(wèn)了this._data.message。所以我們能獲取到this.message的值。
本次給大家推薦一個(gè)免費(fèi)的交流裙,里面概括移動(dòng)應(yīng)用網(wǎng)站開(kāi)發(fā),css,html,webpack,vue node angular以及面試資源等。

對(duì)web開(kāi)發(fā)技術(shù)感興趣的同學(xué),歡迎加入,不管你是小白還是大牛我都?xì)g迎,還有大牛整理的一套高效率學(xué)習(xí)路線和教程與您免費(fèi)分享,同時(shí)每天更新視頻資料。

最后,祝大家早日學(xué)有所成,拿到滿意offer,快速升職加薪,走上人生巔峰。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 數(shù)據(jù)驅(qū)動(dòng) Vue.js 一個(gè)核心思想就是數(shù)據(jù)驅(qū)動(dòng) 類比: jquery缺點(diǎn):直接操作dom 增加內(nèi)存使用(把DOM...
    俺是種瓜低閱讀 985評(píng)論 0 2
  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內(nèi)容,還有我對(duì)于 Vue 1.0 印象不深的內(nèi)容。關(guān)于...
    云之外閱讀 5,178評(píng)論 0 29
  • 組件(Component)是Vue.js最核心的功能,也是整個(gè)架構(gòu)設(shè)計(jì)最精彩的地方,當(dāng)然也是最難掌握的。...
    六個(gè)周閱讀 5,770評(píng)論 0 32
  • 書籍:《少有人走的路 心智成熟的旅程》 作者:M.斯科特·派克 知識(shí)點(diǎn): 推遲滿足感,就是不貪圖暫時(shí)的安逸,先苦后...
    Echo_dc7d閱讀 111評(píng)論 0 0
  • 如果結(jié)果不如你所愿,那就在塵埃落定前奮力一搏 我必須承認(rèn)生命中大部分時(shí)光是屬于孤獨(dú)的,努力成長(zhǎng)是在...
    晨漪閱讀 529評(píng)論 8 7

友情鏈接更多精彩內(nèi)容