在平常工作中,我们有时候会使用到 Vue.extend() 函数,该函数一般是传入一个 组件对象,返回一个构造函数。在以该构造函数创建一个组件实例时,传入的组件对象作为 options 被使用。下面我们来看一下 extend() 函数的内部代码。

  /**
   * Each instance constructor, including Vue, has a unique
   * cid. This enables us to create wrapped "child
   * constructors" for prototypal inheritance and cache them.
   */
  Vue.cid = 0
  let cid = 1
  Vue.extend = function (extendOptions: Object): Function {
    extendOptions = extendOptions || {}
    //this为Vue构造函数
    const Super = this;
    const SuperId = Super.cid
    const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {})
    if (cachedCtors[SuperId]) {
      return cachedCtors[SuperId]
    }
    const name = extendOptions.name || Super.options.name;
    //用于暴露到外面去的构造函数
    const Sub = function VueComponent (options) {
      this._init(options)
    }
    //继承Vue的原型
    Sub.prototype = Object.create(Super.prototype)
    //上一步的操作将其constructor修改了,这里 将constructor指向自己
    Sub.prototype.constructor = Sub
    //合并options项
    Sub.options = mergeOptions(
      Super.options,
      extendOptions
    )
    Sub['super'] = Super;
     Sub.cid = cid++
    if (Sub.options.props) {
      initProps(Sub)
    }
    if (Sub.options.computed) {
      initComputed(Sub)
    }
    //给构造函数挂载属性
    Sub.extend = Super.extend
    Sub.mixin = Super.mixin
    Sub.use = Super.use

    // create asset registers, so extended classes
    // can have their private assets too.
    //  ASSET_TYPES = ['component', 'directive', 'filter']
    ASSET_TYPES.forEach(function (type) {
      Sub[type] = Super[type]
    })
    // enable recursive self-lookup
    if (name) {
      Sub.options.components[name] = Sub
    }

    // keep a reference to the super options at extension time.
    // later at instantiation we can check if Super's options have
    // been updated.
    Sub.superOptions = Super.options
    Sub.extendOptions = extendOptions
    Sub.sealedOptions = extend({}, Sub.options)
    // cache constructor
    cachedCtors[SuperId] = Sub
    //返回该构造函数
    return Sub
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

下面是一个简单的例子。

<template>
    <div id="app">
        {{name}}-{{title}}
    </div>
</template>
<script>
    const comp={
        name:'test',
        props:{
            title:String
        }
    }
    const props={
        title:'james'
    }
    let Ctor=Vue.extend(comp)
    //想要给组件传递props,必须在实例化时,传递propsData属性。
    const instance =new Ctor({
        el:"#app",
        data:{
            name:'test'
        },
        propsData:props
    })
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Last Updated: 6/5/2024, 11:48:25 PM