23.组件注册方式

组件注册方式

一个 Vue 组件在使用前需要先被"注册",这样 Vue 才能在渲染模板时找到其对应的实现。组件注册有两种方式:全局注册和局部注册

全局注册

复制代码
import { createApp } from 'vue'
import App from './App.vue'
import GlobalComponent from "./components/GlobalComponent.vue"


const app = createApp(App);
app.component("GlobalComponent",GlobalComponent)
app.mount('#app');

<template>
  <h3>全局应用组件</h3>
</template>

局部注册

全局注册虽然很方便,但有以下几个问题:

  1. 全局注册,但并没有被使用的组件无法在生产打包时被自动移除 (也叫"tree-shaking")。如果你全局注册了一个组件,即使它并没有被实际使用,它仍然会出现在打包后的 JS 文件中
  2. 全局注册在大型项目中使项目的依赖关系变得不那么明确。在父组件中使用子组件时,不太容易定位子组件的实现。和使用过多的全局变量一样,这可能会影响应用长期的可维护性

局部注册需要使用 components 选项

vue 复制代码
<template>
 <GlobalComponent />
</template>
<script>
import GlobalComponent from "./components/GlobalComponent.vue"
export default {
 components:{
  GlobalComponent
  }
}
</script>
<style>
*{
 margin: 0;
 padding: 0;
}
</style>
<style>
*{
 margin: 0;
 padding: 0;
}
</style>
相关推荐
程序员清洒4 小时前
Flutter for OpenHarmony:GridView — 网格布局实现
android·前端·学习·flutter·华为
VX:Fegn08954 小时前
计算机毕业设计|基于ssm + vue超市管理系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·课程设计
0思必得05 小时前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
LawrenceLan5 小时前
Flutter 零基础入门(二十六):StatefulWidget 与状态更新 setState
开发语言·前端·flutter·dart
秋秋小事5 小时前
TypeScript 模版字面量与类型操作
前端·typescript
2401_892000526 小时前
Flutter for OpenHarmony 猫咪管家App实战 - 添加提醒实现
前端·javascript·flutter
Yolanda946 小时前
【项目经验】vue h5移动端禁止缩放
前端·javascript·vue.js
VX:Fegn08957 小时前
计算机毕业设计|基于springboot + vue酒店管理系统(源码+数据库+文档)
vue.js·spring boot·课程设计
广州华水科技7 小时前
单北斗GNSS形变监测一体机在基础设施安全中的应用与技术优势
前端
EndingCoder7 小时前
案例研究:从 JavaScript 迁移到 TypeScript
开发语言·前端·javascript·性能优化·typescript