1.全局组件:
所有地方都可以使用的组件,通过在main里面引入后使用如:card
import card from './components/card.vue'
createApp(App).component('Card',card).mount('#app')
使用时不用引入,直接写标签就可以使用
2.局部组件
和以前vue2时写的那些组件相同,引入->申明->使用
3.递归组件
<!-- 父组件调用子组件-->
<Tree :list="list"></Tree>
//父组件数据
type TreeList={
title:string
children?:TreeList[] | []
}
const list=reactive<TreeList[]>([
{
title:'no.1',
children:[
{
title:'no.1.1',
children:[
{title:'no.1.1.1'}
]
},
{
title:'no.1.2'
}
]
},
{
title:'no.2',
children:[
{
title:'no.2.1'
},
{
title:'no.2.2'
}
]
},
{
title:'no.3',
children:[
{
title:'no.3.1'
},
{
title:'no.3.2'
}
]
}
]
)
<!-- 子组件接收数据并遍 前面的item.title能遍历出第一层,后面的递归遍历出后面的数据 -->
<div class="margin_lf">
<div v-for="(item, index) in list" :key="index">
{{ item.title }}
<Tree v-if="item.children" :list="item.children"></Tree>
</div>
</div>
注:1.调用自身时无需重新引入,只要自身文件名和调用自身的标签名相同可以成功遍历
2.list的类型和上文传下来相同,建议封装成一个ts文件然后引入减少重复代码量
4.动态组件
首先data属性里面绑定组件实例,然后通过component标签动态绑定is属性达到切换组件的目的。
注:1.组件本身有个代理,reactive也有个代理,所以使用marRaw取消组件的代理,提高效率
2.ts里的Pick能裁剪出申明类型的属性
3.切换时会销毁,可通过外层包一个标签<KeepAlive>会去保留组件状态或避免重新渲染。<KeepAlive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。