Vue利用递归的方法,根据id获取对应的字段名(树形数据)

时间:2024-07-09 19:20:34

树形数据源

 options:[{
		ancestors: "0",
		code: "99",
		id: "99",
		name: "测试部门1",
		parentId: "0",
		children: [{
				ancestors: "0,99",
				code: "test",
				id: "1720269456426344449",
				name: "测试子部门1",
				parentId: "99",
				children: [{
						ancestors: "0,99",
						code: "ccc",
						id: "17202694564263444491",
						name: "测试子部门12",
						parentId: "1720269456426344449",
					},

				},
				{
					ancestors: "0,99",
					code: "102",
					id: "1560428307109957633",
					name: "测试子部门2",
					parentId: "99"
				},
				{
					ancestors: "0,99",
					code: "104",
					id: "1560428634399887362",
					name: "测试子部门3",
					parentId: "99"
				},
			]
		}
	],

定义递归函数

//递归
      getTreeName(list, id) {
        for (let i = 0; i < list.length; i++) {
          if (list[i].id === id) {
            return list[i].name
          } else if (list[i].children && list[i].children.length > 0) {
            let res = this.getTreeName(list[i].children, id)
            if (res) {
              return res
            }
          }
        }
      }

定义调用函数

      //树形回显
      streetFormat(item, params) {
        return this.streetType(params, item);
      },
      // 回显
      streetType(datas, value) {
        var actions = [];
        actions.push(this.getTreeName(datas, value))
        return actions.join('');
      },

调用函数

<span v-else-if="item.type === 'street'">
      {{ streetFormat(row[item.name],item.param) }}
</span>

至此回显成功