vue.extend
使用基礎 Vue 構造器函數,通過原型繼承,(返回)創建一個“子類”(構造器)。參數是一個包含組件選項的對象。
const Sub = function VueComponent (options) {
this._init(options)
}
Sub.prototype = Object.create(Super.prototype)
Sub.prototype.constructor = Sub
vue.component
注冊或獲取全局組件。注冊還會自動使用給定的id
設置組件的名稱。內部實質上調用了vue.extend,最后返回"子類"(構造器),這個子類構造器。
vue.component方法的定義中有如下代碼:
// 此處 this 是 Vue ; this.options._base也是Vue ;相當於Vue.extend
definition = this.options._base.extend(definition)
...
return definition
綜合例子如下:
var Component1 = Vue.component('any',{
template:'<div>Component1</div>'
})
var Component2 = Vue.extend({
template:'<div>Component2</div>'
})
console.log(Component1);
console.log(Component2);
var App = Vue.extend({
components:{Component1,Component2},
data() {
return {
a: 12
}
},
template: `<div>
{{this.a}}
<any/>
<Component1/>
<Component2/>
</div>`,
})
new Vue({
render(h){
return h(App)
}
}).$mount('#app')
- 通過components注冊了一個全局any組件,可以在App中直接使用。
- Component1和Component2這兩個構造函數通過局部注冊之后,也可以在App中使用
components:{組件一,組件二}
單文件vue中經常會通過import引入其他組件,然后在本組件中注冊和使用,代碼:
<template>
<Icon/>
</template>
<script>
import Icon from './icon.vue'
console.log(Icon)
export default {
components:{Icon}
}
</script>
打印Icon,發現Icon是一個對象,既可以是對象也可以是函數,Vue內部是如何處理的呢?
在vue內部創建虛擬dom的時候有如下的代碼:
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor)
}
此處的Ctor對應着上面的Icon,當判斷是對象的時候會調用extend方法,也就是vue.extend方法,返回一個子類
構造函數,殊途同歸。