当前位置: 首页 > news >正文

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

1. 局部组件

Card.vue

<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

<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

// 同上

App.vue

<template><div><Card></Card></div>
</template><script setup lang="ts">
</script><style lang="scss" scoped></style>

main.ts

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

// 同上

Tree.vue

<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

<template><div><Card></Card><Tree></Tree></div>
</template><script setup lang="ts">
</script><style lang="scss" scoped></style>

main.ts

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();

在这里插入图片描述

http://www.lryc.cn/news/98465.html

相关文章:

  • vscode开发Go和Java
  • 自定义MVC
  • 简单分享婚宴预订小程序怎么做
  • 【多模态】19、RegionCLIP | 基于 Region 来实现视觉语言模型预训练
  • 本地文件夹上传到Github
  • 云原生|kubernetes|kubernetes集群部署神器kubekey安装部署高可用k8s集群(半离线形式)
  • Vite + Vue3 +TS 项目router配置踩坑记录! ===>“找不到模块“vue-router”或其相应的类型声明。“<===
  • windows安装npm, 命令简介
  • 微信聊天记录监管有多重要?
  • 【数据结构】实验十:哈夫曼编码
  • Linux-head
  • HHDESK便捷功能介绍三
  • 小试梯度下降算法
  • 【React】版本正确安装echarts-liquidfill(水球图表)包引入不成功问题
  • Debian 11 编译安装 git 2.42.0(基于 OpenSSL)
  • 将Linux init进程设置为systemd
  • element-ui form表单的动态rules校验
  • AGI如何提高智力水平
  • 【广州华锐互动】无人值守变电站AR虚拟测控平台
  • 【C语言】文件操作(二)
  • Kotlin小节
  • 西安电子科技大学
  • 【数据挖掘】PCA/LDA/ICA:A成分分析算法比较
  • 微服务模式:业务服务模式
  • idea中创建请求基本操作
  • springboot整合log4j2
  • Linux输出内容到指定文件
  • mysql主从同步怎么跳过错误
  • 【论文阅读】DEPIMPACT:反向传播系统依赖对攻击调查的影响(USENIX-2022)
  • Nginx 功能及配置详解