当前位置:   article > 正文

详解Vue.component和Vue.extend_vue component extends

vue component extends

写在前面

众所周知,Vue 的灵魂在于: 数据驱动视图 + 组件化,本篇将为大家讲解 Vue组件 的创建,还有与其息息相关的 Vue.extend 方法。

core/global-api/assets.js

在这个文件中定义了 Vue.component 方法,我修改了部分源码便于理解,但准确度不变:

Vue.component = function(id, definition) {
   
  if (!definition) {
   
    return this.options.components[id]
  } else {
   
    if (isPlainObject(definition)) {
   
      definition.name = definition.name || id
      definition = this.options._base.extend(definition)
    }
    this.options.components[id] = definition
    return definition
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

简单解读一下就是:

如果 definition 不存在,说明此前被全局注册过,那就去 Vue.options.components 中找到对应的组件返回;

如果 definition 存在,说明这是一个新的全局组件,需要被全局注册。先判断 definition 是否是一个对象,如果是则将 definition 创建为继承自 Vue构造函数 的子类实例,如果不是则说明是一个已经继承自子类的实例,将其放置到 Vue.options.components 中,然后返回。

有一些绕,那我们就通过代码来进行说明:

// 方式1
const childComponent = Vue.extend({
   
  data: {
   },
  created() {
   },
  methods: {
   },
})
Vue.component('child', childComponent)

// 方式2
Vue.component('child', {
   
  name: 'child-component',
  data: {
   },
  created() {
   },
  methods: {
   },
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/982208
推荐阅读
相关标签
  

闽ICP备14008679号