vue3+ts的全局组件、递归组件

1、vue3如何注册全局组件呢?
首先我们在main.ts中

import { createApp } from 'vue'
import App from './App.vue'
import router from "./router"
import HelloWorld from "./components/HelloWorld.vue"   //引入
const app = createApp(App)
// 挂载到 Vue 根实例将组件
app.use(router)
    .component('Card', HelloWorld)  //注意这个一定放在mount之前
    .mount('#app');

然后我们直接在某个页面组件中使用,如下这样就可以了

<template>
	<div class="home_main">
		<Card></Card>    
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
const menudata = ref(null);
const dataArr = reactive<number[]>([1, 2, 3, 4])


</script>

<style lang="scss">
.home_main {
	width: 100%;
	height: 100%;
	background: #d7d7d7;
	font-size: 30px;
	color: aqua
}
</style>

2、递归组件

跟全局组件的引入方式一致如下是home.vue

<template>
	<div class="home_main">
		<Tree :list="navBarList" />
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
const navBarList = reactive([
	{
		name: '一级导航 1'
	},
	{
		name: '一级导航 2',
		children: [
			{ name: '二级导航 2-1' },
			{
				name: '二级导航 2-2',
				children: [
					{ name: '三级导航 2-2-1' },
					{ name: '三级导航 2-2-2' },
				]
			},
			{ name: '二级导航 2-2' }
		]
	},
	{
		name: '一级导航 3'
	}
])

</script>

<style lang="scss">
.home_main {
	width: 100%;
	height: 100%;
	background: #d7d7d7;
	font-size: 30px;
	color: aqua
}
</style>

如下是Tree组件

<template>
    <ul>
        <template v-for="(item, index) in list" :key="index">
            <li>{{ item.name }}</li>
            <Tree v-if="'children' in item" :key="item" :list="item.children" />
        </template>
    </ul>
</template>
 
<script setup lang="ts">
const props = defineProps({
    list: {
        type: Array,
        default: () => []
    }
})
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值