id vue 取对象_vue递归查找id对应的对象

本文介绍如何在Vue中通过递归遍历树形结构数据,查找指定ID的对象并将其存储到数组中。示例代码展示了一个存在错误的递归函数,该函数试图在树结构`items`中找到ID匹配的子对象,并将其添加到`selections`数组。问题在于当没有找到匹配项时,`result`未被正确处理,导致返回`undefined`。
摘要由CSDN通过智能技术生成

将递归得到的对象push到数组中

let selections = [];

for (let leaf of this.tree) {

let result = this.recursion(this.items, leaf);

selections.push(result);

}

递归函数

recursion(data, id) {

let result;

if (!data) {

return;

}

for (var i = 0; i < data.length; i++) {

let item = data[i];

if (item.id === id) {

result = item;

break;

} else if (item.children && item.children.length > 0) {

result = this.recursion(item.children, id);

}

}

console.log(result);

return result;

},

this.items为树结构的数据

items: [

{

id: 1,

name: 'Vuetify Human Resources',

children: [

{

id: 2,

name:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Ant Design Vue 2.0 提供了一个递归组件 `a-tree`,可以用来实现递归菜单。 首先,需要在组件中引入 `a-tree` 组件: ```vue <template> <a-tree :tree-data="treeData"> <template v-slot="{data}"> <span>{{ data.title }}</span> </template> </a-tree> </template> <script> import { ATree } from 'ant-design-vue' export default { name: 'RecursiveMenu', components: { ATree }, data() { return { treeData: [ { title: 'Menu 1', key: '1', children: [ { title: 'Submenu 1-1', key: '1-1', children: [ { title: 'Sub-submenu 1-1-1', key: '1-1-1' }, { title: 'Sub-submenu 1-1-2', key: '1-1-2' } ] }, { title: 'Submenu 1-2', key: '1-2' } ] }, { title: 'Menu 2', key: '2', children: [ { title: 'Submenu 2-1', key: '2-1' }, { title: 'Submenu 2-2', key: '2-2' } ] } ] } } } </script> ``` 在 `treeData` 中定义了一个递归菜单的数据结构,其中每个菜单项都有一个 `title` 和一个 `key`,以及可能有 `children`,用于定义子菜单。在模板中,使用 `a-tree` 组件来渲染递归菜单,并使用插槽来定义每个菜单项的渲染方式。 在 `a-tree` 组件中,使用 `tree-data` 属性来传递菜单数据。在插槽中,使用 `data` 对象来获当前菜单项的数据,其中包含菜单项的 `title`、`key`、`children` 等信息。 通过这种方式,就可以实现一个简单的递归菜单。需要注意的是,`a-tree` 组件本身提供了许多属性和事件,可以用来控制菜单的交互方式,例如菜单的展开、收起、选中等。具体使用方式可以参考 Ant Design Vue 2.0 官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值