【Vue3】局部组件和全局组件

1. 局部组件

Card.vue

js 复制代码
<template>
  <div class="card">
    <header>
      <div>标题</div>
      <div>副标题</div>
    </header>
    <section>内容</section>
  </div>
</template>

<script setup lang="ts">

</script>

<style lang="less" scoped>
@border: #ccc;
.card {
  border: 1px solid @border;
  width: 400px;
  header {
    display: flex;
    justify-content: space-between;
    padding: 5px;
    border-bottom: 1px solid @border;
  }
  section{
    padding: 5px;
    min-height: 300px;
  }
}
</style>

App.vue

js 复制代码
<template>
  <div>
    <CardVue></CardVue>
  </div>
</template>

<script setup lang="ts">
import CardVue from './components/Card.vue'

</script>

<style lang="scss" scoped>

</style>

2. 全局组件

2.1 注册单个全局组件

Cardvue

js 复制代码
// 同上

App.vue

js 复制代码
<template>
  <div>
    <Card></Card>
  </div>
</template>

<script setup lang="ts">
</script>

<style lang="scss" scoped></style>

main.ts

js 复制代码
import { createApp } from 'vue'
import App from './App.vue'
import CardVue from './components/Card.vue'
export const app = createApp(App)
app.component('Card', CardVue)
app.mount('#app')

2.2 批量注册全局组件

Card.vue

js 复制代码
// 同上

Tree.vue

js 复制代码
<template>
  <div>
      <h1>this is a title</h1>
  </div>
</template>

<script setup lang="ts">
</script>

<style lang="scss" scoped>
h1 {
  border: 1px solid black;
}
</style>

App.vue

js 复制代码
<template>
  <div>
    <Card></Card>
    <Tree></Tree>
  </div>
</template>

<script setup lang="ts">
</script>

<style lang="scss" scoped></style>

main.ts

js 复制代码
import { createApp, defineAsyncComponent } from 'vue'
import App from './App.vue'
const app = createApp(App)
const componentNames = ['Card', 'Tree'];
// 使用动态导入的方式注册全局组件时需要注意异步组件的加载
// 异步组件使用 defineAsyncComponent 方法来处理动态导入的组件,并且使用 await 关键字等待组件的加载完成。在组件加载完成后,再将其注册为全局组件。
// 如果没有注意异步组件的加载,会报 Invalid VNode type: undefined (undefined) 的问题
async function registerComponents() {
  for (const componentName of componentNames) {
    // 使用 defineAsyncComponent 方法动态导入异步组件
    const component = await defineAsyncComponent(() => import(`./components/${componentName}.vue`));
    app.component(componentName, component);
  }
  app.mount('#app');
}
registerComponents();
相关推荐
胡萝卜术5 小时前
从API调用到手写LRU:力扣146「LRU缓存」的哈希表+双向链表终极进化之路
前端·javascript·面试
科技道人5 小时前
记录 默认置灰/禁用 app ‘Search Engine Selector‘ 的disable按钮
开发语言·前端·javascript
天疆说5 小时前
Zotero Connector 在 Edge 里找不到桌面 Zotero(Linux / Zotero 9.0.6 / Edge 150)
linux·前端·edge
李伟_Li慢慢6 小时前
02-从硬件说起WebGL
前端·three.js
kyriewen7 小时前
看了微软几万人用AI编程的数据——效率涨24%的代价没人提
前端·ai编程·claude
2601_963771377 小时前
How to Scale Your WordPress Store Traffic in 2026
前端·php·plugin
亿元程序员8 小时前
老板说我的3D箭头游戏用来做试玩太普通了,没人想玩,让我变点花样...
前端
李伟_Li慢慢8 小时前
01-threejs架构原理-课程简介
前端·three.js
_瑞10 小时前
深入理解 iOS 渲染原理
前端·ios
IT_陈寒10 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端