3.最俗學(xué)習(xí)之-Vue源碼學(xué)習(xí)-引入篇(下)

源碼地址

文件:src/core/instance/init.js

這個(gè)就是Vue引入初始化的最后一個(gè)文件了

這里執(zhí)行5個(gè)方法,參數(shù)都是Vue構(gòu)造函數(shù)


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


這里就直接引用大神的分析的結(jié)果了

引入依賴,定義 Vue 構(gòu)造函數(shù),然后以Vue構(gòu)造函數(shù)為參數(shù),調(diào)用了五個(gè)方法,最后導(dǎo)出 Vue。這五個(gè)方法分別來自五個(gè)文件:init.js state.js render.js events.js 以及 lifecycle.js。
打開這五個(gè)文件,找到相應(yīng)的方法,你會發(fā)現(xiàn),這些方法的作用,就是在 Vue 的原型 prototype 上掛載方法或?qū)傩?,?jīng)歷了這五個(gè)方法后的Vue會變成這樣:


// initMixin(Vue)    src/core/instance/init.js **************************************************
Vue.prototype._init = function (options?: Object) {}

// stateMixin(Vue)    src/core/instance/state.js **************************************************
Vue.prototype.$data
Vue.prototype.$set = set
Vue.prototype.$delete = del
Vue.prototype.$watch = function(){}

// renderMixin(Vue)    src/core/instance/render.js **************************************************
Vue.prototype.$nextTick = function (fn: Function) {}
Vue.prototype._render = function (): VNode {}
Vue.prototype._s = _toString
Vue.prototype._v = createTextVNode
Vue.prototype._n = toNumber
Vue.prototype._e = createEmptyVNode
Vue.prototype._q = looseEqual
Vue.prototype._i = looseIndexOf
Vue.prototype._m = function(){}
Vue.prototype._o = function(){}
Vue.prototype._f = function resolveFilter (id) {}
Vue.prototype._l = function(){}
Vue.prototype._t = function(){}
Vue.prototype._b = function(){}
Vue.prototype._k = function(){}

// eventsMixin(Vue)    src/core/instance/events.js **************************************************
Vue.prototype.$on = function (event: string, fn: Function): Component {}
Vue.prototype.$once = function (event: string, fn: Function): Component {}
Vue.prototype.$off = function (event?: string, fn?: Function): Component {}
Vue.prototype.$emit = function (event: string): Component {}

// lifecycleMixin(Vue)    src/core/instance/lifecycle.js **************************************************
Vue.prototype._mount = function(){}
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {}
Vue.prototype._updateFromParent = function(){}
Vue.prototype.$forceUpdate = function () {}
Vue.prototype.$destroy = function () {}

到了這里,引入Vue這個(gè)構(gòu)造函數(shù)的初始化就基本告一段落了,接下來就是我們要?jiǎng)?chuàng)建一個(gè)實(shí)例了
這里還是采用大神的例子


let v = new Vue({
    el: '#app',
    data: {
        a: 1,
        b: [1, 2, 3]
    }
})

// 然后就會走這個(gè)方法

Vue.prototype._init = function (options?: Object) {
  const vm: Component = this
  // a uid
  vm._uid = uid++
  // 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)
  callHook(vm, 'beforeCreate')
  initState(vm)
  callHook(vm, 'created')
  initRender(vm)
}

// 這里的if (options && options._isComponent)就不說了,看了很多教程都跳過這里,因?yàn)檫@里是
// 內(nèi)部使用的,我們主要看這兩個(gè)方法mergeOptions和resolveConstructorOptions(vm.constructor)
// 先說這個(gè)resolveConstructorOptions,如果按照平常的套路這里就會直接返回我們傳入的options參數(shù)
// 這里個(gè)人好奇的用了一個(gè)簡單的例子嘗試了一下,看看它的作用是什么

<p style="font-weight: bold;margin-bottom: 10px;color: blue">
resolveConstructorOptions之個(gè)人試用
</p>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>resolveConstructorOptions之個(gè)人試用</title>
</head>
<body>
  <div id="app">
    <p style="color: blue">{{msg}}</p>
    <p style="color: blue">{{name}}</p>
    <p style="color: blue">{{cpName}}</p>
    <button v-on:click="clickMe">click me</button>
  </div>
</body>
<script type="text/javascript" src="vue.js"></script>
<script>

Vue.super = {
  options: {
    data () {
      return {
        name: 'super defined',
        msg: 'hello world from Vue.super'
      }
    },
    computed: {
      cpName () {
        return this.name + ' from Vue.super'
      }
    },
    methods: {
      clickMe () {
        alert('click form Vue.super')
      }
    }
  }
}

Vue.extendOptions = {

}

var options = {
  el: '#app',
  data () {
    return {
      msg: 'hello world'
    }
  },
  methods: {
    clickMe () {
      alert('click form new Vue')
    }
  }
}


var myVue = new Vue(options)

console.log(myVue)
</script>
</html>


<span style="color: blue">上面的例子直接復(fù)制到瀏覽器打開即可看到效果,這里我們看到new Vue的數(shù)據(jù)會把Vue.super的數(shù)據(jù)覆蓋,
如果沒有的話,則會使用Vue.super的數(shù)據(jù),感覺有點(diǎn)像是合并參數(shù)的樣子,但是這個(gè)東西肯定不是這樣用的,
這里還是坐等大神解釋這個(gè)高級的用法,這里就不做深入研究了,因?yàn)橐话愣己苌儆玫竭@種情況</span>


// 那么這里就直接是返回Vue.options了,也就是之前說過的這個(gè)東西


Vue.options = {
    components: {
        KeepAlive,
        Transition,
        TransitionGroup
    },
    directives: {
        model,
        show
    },
    filters: {},
    _base: Vue
}

// 至于options則是我們傳入的各種參數(shù),按照上面的例子則是這樣的,這里也直接從大神文章里面復(fù)制過來了

vm.$options = mergeOptions(
    // Vue.options
  {
      components: {
          KeepAlive,
          Transition,
          TransitionGroup
      },
      directives: {
          model,
          show
      },
      filters: {},
      _base: Vue
  },
  // 調(diào)用Vue構(gòu)造函數(shù)時(shí)傳入的參數(shù)選項(xiàng) options
  {
      el: '#app',
      data: {
          a: 1,
          b: [1, 2, 3]
      }
  },
  // this
  vm
)


src/core/util/options.js

順著路徑我們找到這個(gè)文件,在264行里就可以看到這個(gè)方法,這個(gè)是Vue的合并策略方法,再看源碼之前,
有看過很多的文章,其中這個(gè)方法非常<span style="font-weight: bold;color: red;">重要!重要!重要!</span>
這里打算把這個(gè)東西研究的盡量深入一點(diǎn),以免后面各種懵逼,首先我們從最頂部開始


const strats = config.optionMergeStrategies;

定義一個(gè)全局變量,然而optionMergeStrategies: Object.create(null),所以就是

const strats = {}

strats.el = strats.propsData = function (parent, child, vm, key) {
  return defaultStrat(parent, child)
}

strats.data = function (
  parentVal: any,
  childVal: any,
  vm?: Component
) {}


// 然后還有這兩個(gè)東東,找到config.js下面的兩個(gè)變量,其實(shí)就是兩個(gè)數(shù)組
config._lifecycleHooks.forEach(hook => {
  strats[hook] = mergeHook
})

config._assetTypes.forEach(function (type) {
  strats[type + 's'] = mergeAssets
})


/**
 * List of asset types that a component can own.
 */
_assetTypes: [
  'component',
  'directive',
  'filter'
],

/**
 * List of lifecycle hooks.
 */
_lifecycleHooks: [
  'beforeCreate',
  'created',
  'beforeMount',
  'mounted',
  'beforeUpdate',
  'updated',
  'beforeDestroy',
  'destroyed',
  'activated',
  'deactivated'
],

// 經(jīng)過這一段操作后,則strats變成了下面這樣

strats = {
  el: function (parent, child, vm, key) {
    return defaultStrat(parent, child)
  },
  propsData: function (parent, child, vm, key) {
    return defaultStrat(parent, child)
  },
  data: function (parentVal: any,childVal: any,vm?: Component) {
    do something...
  },
  beforeCreate: function mergeHook () {
    do something...
  },
  created: function mergeHook () {
    do something...
  },
  beforeMount: function mergeHook () {
    do something...
  },
  mounted: function mergeHook () {
    do something...
  },
  beforeUpdate: function mergeHook () {
    do something...
  },
  updated: function mergeHook () {
    do something...
  },
  beforeDestroy: function mergeHook () {
    do something...
  },
  destroyed: function mergeHook () {
    do something...
  },
  activated: function mergeHook () {
    do something...
  },
  deactivated: function mergeHook () {
    do something...
  },
  components: function mergeAssets () {  // 這里加上個(gè)s復(fù)數(shù)
    do something...
  },
  directives: function mergeAssets () {  // 這里加上個(gè)s復(fù)數(shù)
    do something...
  },
  filters: function mergeAssets () {  // 這里加上個(gè)s復(fù)數(shù)
    do something...
  },
  watch: function (parentVal: ?Object, childVal: ?Object) {
    do something...
  },
  props: function (parentVal: ?Object, childVal: ?Object) {
    do something...
  },
  methods: function (parentVal: ?Object, childVal: ?Object) {
    do something...
  },
  computed: function (parentVal: ?Object, childVal: ?Object) {
    do something...
  }
}

這樣子就清晰多了,引用大神的話就是這樣的:

“config 對象引用自 src/core/config.js 文件,最終的結(jié)果就是在 strats 下添加了相應(yīng)的生命周期選項(xiàng)的合并策略函數(shù)為 mergeHook,添加指令(directives)、組件(components)、過濾器(filters)等選項(xiàng)的合并策略函數(shù)為 mergeAssets?!?/p>

<span style="color: red;font-weight: bold;">回到主題</span>


vm.$options = mergeOptions(
    // Vue.options
  {
      components: {
          KeepAlive,
          Transition,
          TransitionGroup
      },
      directives: {
          model,
          show
      },
      filters: {},
      _base: Vue
  },
  // 調(diào)用Vue構(gòu)造函數(shù)時(shí)傳入的參數(shù)選項(xiàng) options
  {
      el: '#app',
      data: {
          a: 1,
          b: [1, 2, 3]
      }
  },
  // this
  vm
)

// 方法首先執(zhí)行checkComponents(child),其中涉及兩個(gè)方法isBuiltInTag和isReservedTag,后者已經(jīng),
// 說過前面兩個(gè)方法在methods realizes目錄查看,所以這里就是禁止使用html標(biāo)簽svg標(biāo)簽還有slot,component這兩個(gè)
// 作為組件名字,當(dāng)然我們這個(gè)例子不會有問題,因?yàn)槲覀儧]有用到組件components來注冊
// 然后再到了normalizeProps(child)和normalizeDirectives(child)還是在methods realizes目錄說明
// 這里我們使用的例子沒有props字段,在方法解釋里面我們模擬一個(gè)即可,這里面還有個(gè)camelize方法,也
// 一起放在methods realizes目錄下,那么這三個(gè)方法大概如下
// camelize  =>  字符串轉(zhuǎn)駝峰
// normalizeProps  =>  標(biāo)準(zhǔn)化props字段的格式
// normalizeDirectives  =>  標(biāo)準(zhǔn)化directives字段的格式

// 然后到了下面這一段,這里不明白具體功能,先不管

const extendsFrom = child.extends
if (extendsFrom) {
  parent = typeof extendsFrom === 'function'
    ? mergeOptions(parent, extendsFrom.options, vm)
    : mergeOptions(parent, extendsFrom, vm)
}

// 這一段留到下一篇再講,順便把之前留的一個(gè)問題也解決了

if (child.mixins) {
  for (let i = 0, l = child.mixins.length; i < l; i++) {
    let mixin = child.mixins[i]
    if (mixin.prototype instanceof Vue) {
      mixin = mixin.options
    }
    parent = mergeOptions(parent, mixin, vm)
  }
}

// 這一段將會舉N多個(gè)例子來測試,盡量把這個(gè)合并策略弄懂,因?yàn)檫@個(gè)是Vue的精粹之一

const options = {}
let key
for (key in parent) {
  mergeField(key)
}
for (key in child) {
  if (!hasOwn(parent, key)) {
    mergeField(key)
  }
}
function mergeField (key) {
  const strat = strats[key] || defaultStrat
  options[key] = strat(parent[key], child[key], vm, key)
}
return options


<p style="font-weight: bold;margin-bottom: 10px;color: #FF0000">剩下的幾個(gè)問題</p>


Vue.set = set                       // 涉及到Vue的數(shù)據(jù)響應(yīng)式系統(tǒng),先保留
Vue.delete = del                    // 涉及到Vue的數(shù)據(jù)響應(yīng)式系統(tǒng),先保留
Vue.nextTick = util.nextTick        // 水平有限,看不懂 - -#
initMixin(Vue)                      // 這個(gè)后面再講
initExtend(Vue)                     // 水平有限,看不懂 - -#


extend(Vue.options.directives, platformDirectives)  // 水平有限,看不懂 - -#
extend(Vue.options.components, platformComponents)  // 水平有限,看不懂 - -#
Vue.prototype.__patch__                             // 水平有限,看不懂 - -#
compileToFunctions                                  // 水平有限,看不懂 - -#


const extendsFrom = child.extends                   // 水平有限,看不懂 - -#

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

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

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