我有一个一维嵌套数组:nestedObj: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 2, parentId: 1, taskCode: '12100', taskName: 'Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 3, parentId: 2, taskCode: '12200', taskName: 'SubChild one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 4, parentId: 1, taskCode: '12200', taskName: 'Child two', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}]根据上述数据结构,树视图taskName如下所示-> Parent -> Child one -> SubChild one -> Child two这是我的问题:当我更新startDate一个孩子的 时,它的直接父母startDate应该用(所有孩子的)最小值进行更新startDate,并且这个过程应该传播到根。对于(即) (其所有子项)的endDate最大值,反之亦然。startDate我如何使用递归来实现这一点?
1 回答
繁花不似锦
TA贡献1851条经验 获得超4个赞
您需要的递归函数将如下所示:
methods: {
adjustParent(item) {
if (!item.parentId) return; // top-level, exit
const parent = this.nestedObj.find(o => o.id === item.parentId);
const children = this.nestedObj.filter(o => o.parentId === item.parentId);
parent.startDate = Math.min.apply(null, children.map(o => o.startDate));
this.adjustParent(parent); // recurse
}
}
change例如,您可以调用它:
<div v-for="item in nestedObj">
<input type="text" v-model="item.startDate" @change="adjustParent(item)" />
</div>
添加回答
举报
0/150
提交
取消