今天我们来了解vue组件注册的内容,下文会给大家介绍vue组件注册的两种方式, 全局组件的注册方法和局部组件的注册方法,下文示例有一定的参考价值,需要的朋友可以了解看看。
一、了解组件注册的两种方式
1.1 全局组件的注册方法
//main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
let Hello = {
name: 'hello',
template: '这是全局组件hello'
}
Vue.component('hello', Hello)
new Vue({
el: '#app',
router,
components: { App },
template: ''
})
上面我们就通过Vue.component()注册了一个全局组件hello,接下来分析源码实现的时候也是基于这个例子来进行的。
1.2 局部组件的注册
<template>
<div id="app">
<img src="./assets/logo.png">
<HelloWorld/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components:{
HelloWorld
}
}
</script>
像这样就注册了一个HelloWorld的局部组件。
二、全局组件注册的源码
1.Vue初始化的时候,会调用initGlobalAPI()
//【代码块1】
//代码所在文件:src/core/global-api/index.js
export function initGlobalAPI(Vue: GlobalAPI){
//...省略其他无关代码
initAssetRegisters(Vue)
//这个方法就是用于组件注册的方法
}
2.在initAssetRegisters()方法中执行组件的定义
//【代码块2】
//代码所在文件:src/core/global-api/assets.js
export function initAssetRegister(Vue){
ASSET_TYPES.forEach(type=>{
//ASSET_TYPES包括component、directive、filter
Vue[type] = function(id, definition){
//...一些条件判断
if(type === 'component' && isPlainObject(definition)){
definition.name = definition.name || id
definition = this.options._base.extend(definition)
//将definition转换为一个继承于Vue的构造函数
}
//...其他类型的处理
this.options[type+'s'][id] = definition //将这个构造函数挂载到Vue.options.components上
return definition
}
})
}
此时,我们可以单步调试一下我们上面的例子,来看一下definition一开始是什么,以及执行挂载后Vue.options变成了什么样子:
a.definition: 其实传入的时候就是我们一开始定义的全局组件的具体内容
b.Vue.options: 可以看到我们定义的全局组件hello已经存在在Vue.options.components上了
大型站长资讯类网站! https://www.0833zz.com