vue实现递归组件

父组件:

    <Tree :data="data"></Tree>
import Tree from "@/components/Tree.vue";
const data = reactive([
  {
    name: "1",
    checked: true,
    children: [
      {
        name: "1-1",
        checked: false,
      },
    ],
  },)

子组件:

<template>
  <div class="tree" v-for="item in data" :key="item.name">
    <input v-model="item.checked" type="checkbox" />
    <span>{{ item.name }}</span>
    <Tree v-if="item?.children?.length" :data="item?.children"></Tree>
  </div>
</template>

<script setup>
let props = defineProps({
  data: Array,
});
</script>
  • 13
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue递归组件可以用于渲染树形结构,可以通过自定义递归组件实现树形结构的展开和收起。 以下是一个简单的实现示例: 组件代码: ``` <template> <ul> <li v-for="item in items" :key="item.id"> <span class="toggle" @click="toggle(item)">{{ item.expanded ? '-' : '+' }}</span> <span class="text">{{ item.text }}</span> <tree v-if="item.children && item.expanded" :items="item.children"></tree> </li> </ul> </template> <script> export default { name: 'tree', props: { items: { type: Array, required: true } }, methods: { toggle(item) { item.expanded = !item.expanded; } } }; </script> <style scoped> ul { list-style: none; padding-left: 10px; } .toggle { display: inline-block; width: 20px; text-align: center; cursor: pointer; } .text { margin-left: 5px; } </style> ``` 上述代码中,我们定义了一个递归组件`tree`,用于渲染树形结构。该组件包含一个`items`属性,用于传入树形结构的数据。在组件的模板中,使用`v-for`指令遍历`items`数组,渲染每个节点。对于每个节点,我们添加了一个展开/收起按钮,并使用`v-if`指令判断子节点是否需要渲染。在点击展开/收起按钮时,调用`toggle`方法来切换节点的展开状态。 使用该组件时,只需要传入树形结构的数据即可: ``` <template> <div> <tree :items="items"></tree> </div> </template> <script> export default { data() { return { items: [ { id: 1, text: '节点1', expanded: false, children: [ { id: 11, text: '子节点1-1', expanded: false, children: [] }, { id: 12, text: '子节点1-2', expanded: false, children: [] } ] }, { id: 2, text: '节点2', expanded: false, children: [ { id: 21, text: '子节点2-1', expanded: false, children: [] }, { id: 22, text: '子节点2-2', expanded: false, children: [] } ] } ] }; } }; </script> ``` 这样,当用户点击节点的展开/收起按钮时,就会切换节点的展开和收起状态,并相应地展开或收起节点的子节点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TechWhiz-晓同

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值