【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();
相关推荐
Highcharts.js26 分钟前
Highcharts 云端渲染的真相:交互式图表与服务器端生成的边界
前端·信息可视化·服务器渲染·highcharts·图表渲染
zhuyan1081 小时前
Linux 系统磁盘爆满导致无法启动修复指南
前端·chrome
编程牛马姐2 小时前
独立站SEO流量增长:提高Google排名的优化方法
前端·javascript·网络
NotFound4862 小时前
实战指南如何实现Java Web 拦截机制:Filter 与 Interceptor 深度分享
java·开发语言·前端
Dontla2 小时前
高基数(High Cardinality)问题介绍(Prometheus、高基数字段、低基数字段)
前端·数据库·prometheus
一 乐3 小时前
医院挂号|基于springboot + vue医院挂号管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·医院挂号管理系统
whuhewei5 小时前
为什么客户端不存在跨域问题
前端·安全
妮妮喔妮5 小时前
supabase的webhook报错
开发语言·前端·javascript
qq_12084093715 小时前
Three.js 大场景分块加载实战:从全量渲染到可视集调度
开发语言·javascript·数码相机
yivifu5 小时前
手搓HTML双行夹批效果
前端·html·html双行夹注