解析 " 命名空间组件" 到底是什么东西
前言
在使用 Vue3 的过程当中, 在学习语法糖的时候,发现了 命名空间组件这个名词,在此之前并未了解过,来浅浅的研究一下 ~
一、命名空间组件是什么?
以下介绍来自官方文档
二、分析理解
1.从单个文件中导入多个组件 – 分别引入
首先创建三个组件 : componentA
, componentb
, componentC
创建一个 child.js 引入这三个组件并抛出
// child.js
// 引入组件
import ComponentA from './componentA.vue'
import ComponentB from './ComponentB.vue'
import ComponentC from './ComponentC.vue'
// 抛出组件
export {
ComponentA,
ComponentB,
ComponentC
}
在父组件中引入 child.js ,并使用 child.js 中的三个组件
<!-- father.vue -->
<template>
<div>
<h2>我是父组件!</h2>
<!-- 使用三个组件 -->
<ComponentA></ComponentA>
<ComponentB></ComponentB>
<ComponentC></ComponentC>
</div>
</template>
// father.vue
<script setup>
// 从 child.js 中引入三个组件
import {ComponentA,ComponentB,ComponentC} from './child'
</script>
这时候页面中的效果如下
2.从单个文件中导入多个组件 – 使用命名空间的方式引入
代码如下(示例):
<!-- father.vue -->
<template>
<div>
<h2>我是父组件!</h2>
<!-- 使用三个组件 -->
<Child.ComponentA></Child.ComponentA>
<Child.ComponentB></Child.ComponentB>
<Child.ComponentC></Child.ComponentC>
</div>
</template>
<script setup>
// 从 child.js 中引入三个组件
import * as Child from './child'
</script>
此处的效果是一样的 ~ ! !
总结
使用 命名空间组件
的引入组件的方式方便之处就是如果需要引入一个文件
中的多个组件
,就不用一个一个引入了,可以 import * as Xxx from 'xxx'
将整个文件引入
antdesign 中已经有这样的用法了,组件之间的关系更加明确,有一个相同父级
<template>
<Form.Input>
<Form.Label>label</Form.Label>
</Form.Input>
</template>
<script setup>
import * as Form from './form-components'
</script>
前提
使用命名空间组件是有前提的 ! : 必须是 Vue3 中 setup 语法糖
的格式才可以使用,直接在 Vue3 中使用是不生效的 (有看到文章中说必须是 Vue3+ ts ,我在 Vue3 setup script 语法糖中不使用 ts 的情况下试了试,是可以的)
不使用 Vue3 语法糖的方式,会有 warn 并且页面中不展示内容了