1. 程式人生 > >vue原始碼分析1-new Vue做了哪些操作

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

首先我們可以看到vue的原始碼在github上有,大家可以克隆下來。 git地址 我們主要看src下的內容。

1.現在我們來分析下 new Vue都做了哪些操作

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

我們都知道new關鍵字在js中代表例項化一個物件,而vue實際上是一個類,類在js中是用Function來實現的,在原始碼的

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只能通過new關鍵字初始化,然後會呼叫this._init方法,同時把options引數傳入,_init是vue原型上的一個方法。那麼接下來我們看下_init方法做了些什麼。在initMixin中定義了_init方法。

src/core/instance/init.js中

 Vue.prototype._init = function (options?: Object) {
    // this指向Vue的例項,所以這裡是將Vue的例項快取給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)// 呼叫vm上的$mount方法去掛載
    }
  }
複製程式碼

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

當我們在chrome的console中可以看到打印出來的data.message的值。試想一下,為什麼我們能夠輸出這個值呢?帶著這個問題我們來看看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型別是否是一個function,並賦值給vm._data
    ? getData(data, vm)
    : data || {}
  if (!isPlainObject(data)) {  //判斷data是否是一個物件,如果不是,報一堆警告
    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
    )
  }
  // 拿到物件的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 */)
}
複製程式碼

當我們的data是一個函式的時候,會去呼叫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()
  }
}
複製程式碼

我們拿到物件的keys,props,methods時進行一個迴圈判斷,我們在data上定義的屬性值有沒有在props中也被定義,如果有,則報警告,這是因為我們定義的所有值最終都會繫結到vm上,通過proxy實現,呼叫proxy,將_data作為sourceKey傳入。

export function proxy (target: Object, sourceKey: string, key: string) {
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]  //vm._data.key會訪問這
  }
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}
複製程式碼

通過這個物件定義了一個get,set。當我們訪問this.message時也就是訪問了this._data.message。所以我們能獲取到this.message的值。

以上是個人通過視訊、檢視各位大佬的文章總結的,後續還會有其他文章釋出,如有不足之處,歡迎大家來討論。