全局组件
封装Card全局组件
<template>
<div>
<div>
<div>卡片一级标题</div>
<div>卡片二级标题</div>
</div>
<div v-if='content'>{{content}}</div>
</div>
</template>
<script setup lang="ts">
// 接收调用者传来的值
type Props = {
content?: string
}
defineProps<Props>()
</script>
全局注册(main.ts)
// 注册全局组件
import Card from './components/Card.vue'
//注意:在main.ts 引入我们的组件跟随在createApp(App)后面,切记不能放到mount后面这是一个链式调用
// 注册组件的名字 组件实例
createApp(App).component('Card',Card).mount('#app')
使用
<Card content="使用全局组件"></Card>
局部组件
在一个组件内通过import去引入别的组件
递归组件
自身去调用自身,需要一个条件来结束递归,否则导致内存泄漏
封装递归Tree组件
<template>
<div v-for="(item,index) in data" :key="index">
{{item.name}}
//使用递归组件 v-if为结束递归的条件
<TreeItem v-if="item.children.length" :data="item.children"></TreeItem>
</div>
</template>
<script setup lang="ts">
//使用递归组件,直接引入自身
import TreeItem from './components/Tree.vue'
//定义一个不确定层级的tree的数据类型
type TreeList = {
name: string,
icon?: string,
children?: TreeList[] | []
}
//定义数据格式
const data = reactive<TreeList[]>([
{
name: tree-1,
children: [
{
name: tree-1-1,
children: [
{
name: tree-1-1-1
}
]
}
]
},
{
name: tree-2,
children: [
{
name: tree-2-1
}
]
},
{
name: tree-3
}
])
</script>
//需要给组件定义类
<script lang="ts">
export default {
name: "TreeItem"
}
</script>
动态组件
vue提供类内置组件component标签,使用:is=”组件”
<template>
<div v-for="item in data" :key="item"{{item.compName}}></div>
<component :is="current.compName"></component>
</template>
<script setup lang="ts">
import A from './A.vue'
import B from './B.vue'
import C from './C.vue'
//定义标签类型
type Tabs = {
name: string,
compName: any
}
//注意:reactive也会对组件进行代理,需要使用markRaw()包裹一下组件跳过proxy代理
const data = reactive<Tabs[]>([
{
name: A组件,
compName: markRaw(A)
},
{
name: B组件,
compName: markRaw(B)
},
{
name: C组件,
compName: markRaw(C)
}
])
//从Tabs类型里面取出compName
type CurrentCom = Pick<Tabs,'compName'>
//定义当前显示组件
const current = reactive<CurrentCom>({
//当前选中默认值
compName: data[0].compName
})
</script>
异步组件(需要配合Suspense使用)
<template>
<Suspense>
//放组件
<template #default>
<AsyncTest></AsyncTest>
</template>
//组件加载的时候
<template #fallback>
<div>loading...</div>
</template>
</Suspense>
</template>
//引入异步组件
const AsyncTest = defineAsyncComponent(() => import('./components/AsyncTest.vue'))