vue3_局部组件,全局组件,递归组件

1.局部组件

<template>
    <child></child>
</template>
<script setup lang="ts">
//引入局部组件,可直接使用
import child from './child.vue'

2.全局组件

  • 单个注册
import child from './views/home/child.vue'
createApp(App).component('child',child).mount('#app')
  • 批量注册
    components文件夹
    install.ts文件:
import type { App } from 'vue'
export default {
    install:(app:App) => {
        const modules:any = import.meta.glob('./**/install.ts')
        for(const path in modules){
            app.use(modules[path].default)
        }
    }
}

main.ts:

import baseComponentsInstall from '@/components/install'
createApp(App).component('baseComponentsInstall',baseComponentsInstall).mount('#app')

3.递归组件

子组件:

<template>
  <div class="card" v-for="item in data">
    <input type="checkbox"><span>{{ item.name }}</span>
    <child v-if="item.children?.length" :data="item.children"></child>
  </div>
</template>
<script setup lang="ts">
import {ref,onMounted, reactive} from 'vue'
interface Tree {
    name:string,
    children?:Tree[]
}
const props = withDefaults(
    defineProps<{
    data?:Tree[]
}>(),{
}
)
</script>

父组件:

<template>
  <div class="container">
    <child :data="data"></child>
  </div>
</template>

<script setup lang="ts">
import HelloWorld from '@/components/HelloWorld.vue';
import {ref,reactive,onBeforeMount, onMounted} from 'vue'
import child from './child.vue'
type TreeList = {
  name: string;
  icon?: string;
  children?: TreeList[] | [];
};
const data = reactive<TreeList[]>([
  {
    name: "no.1",
    children: [
      {
        name: "no.1-1",
        children: [
          {
            name: "no.1-1-1",
          },
        ],
      },
    ],
  },
  {
    name: "no.2",
    children: [
      {
        name: "no.2-1",
      },
    ],
  },
  {
    name: "no.3",
  },
]);
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值