组件的注册
个Vue 组件在使用前需要先被"注册",这样 Vue 才能在染模板时找到其对应的实现。组件注册有两种方式:全局注册和局部注册
全局注册
我们可以使用 Vue 应用实例的 .component() 方法,让组件在当前 Vue 应用中全局可用。
import {
createApp } from 'vue'
import Hander from "vuepath.vue"
const app = createApp({
})
app.component(
// 注册的名字
'MyComponent',
// 组件的实现
{
/* ... */
}
)
aoo.mount*('#app');
全局注册虽然很方便,但有以下几个问题
1、全局注册,但并没有被使用的组件无法在生产打包时被自动移除(也叫”tree-shaking”)。如果你全局注册了一个组件,即使它并没有被实际使用,它仍然会出现在打包后的JS文件中
2、全局注册在大型项目中使项目的依赖关系变得不那么明确。在父组件中使用子组件时,不太容易定位子组件的实现。和使用过多的全局变量一样,这可能会影响应用长期的可维护性
局部注册
<template>
<!--第三步:使用组件-->
<test/>
</template>
<script setup>
//第一步:引入组件
import test from "./components/test.vue"
exprot default{
data(){
//第二步,声明组件(vue3中可以省略此步骤)
test
}
}
</script>
<style>
/* 在这里添加全局样式 */
</style>