注意!!
在使用递归组件+事件的时候,要阻止一下事件冒泡 @click.stop
//Tree.vue
<template>
<div @click.stop="clickItem(item)" v-for="(item, index) in data" :key="index">
<input v-model="item.checked" type="checkbox"> <span>{{ item.name }}</span>
<!-- 递归渲染-默认名字Tree -->
<!-- <Tree v-if="item?.children?.length" :data="item?.children"></Tree> -->
<!-- 递归渲染-自定义名字Yyx-方法一 -->
<!-- <Yyx v-if="item?.children?.length" :data="item?.children"></Yyx> -->
<!-- 递归渲染-自定义名字Xiao-方法二 -->
<Xiao v-if="item?.children?.length" :data="item?.children"></Xiao>
</div>
</template>
<!-- 递归渲染-自定义名字Yyx-方法一 -->
<script lang="ts">
export default {
name:'Yyx'
}
</script>
<script setup lang='ts'>
// 递归渲染-自定义名字Yyx-方法二
defineOptions({
name:'Xiao'
})
defineProps<{
data:any[]
}>()
const clickItem = (item:iTree) =>{
console.log(item)
}
</script>
<style scoped lang='scss'>
</style>
//parent.vue
<template>
<div>
<Tree :data="data"></Tree>
</div>
</template>
<script setup lang='ts'>
import { reactive } from 'vue'
import Tree from '../components/Tree.vue';
interface Tree{
name:string
checked:boolean
children?:Tree[]
}
const data = reactive<Tree[]>([
{
name:'1',
checked:false,
children:[
{
name:'1-1',
checked:false
},
{
name:'1-2',
checked:true
}
]
},
{
name:'2',
checked:false
},
{
name:'3',
checked:false,
children:[
{
name:'3-1',
checked:false,
children:[
{
name:'3-1-1',
checked:false,
},
{
name:'3-1-2',
checked:false,
}
]
}
]
}
])
</script>
<style scoped lang='scss'>
</style>