element ui树形js表格实现增删改查

1. 新增

/**
  * 树形新增事件
  * 添加节点到目标id下
  * list 树形列表数据
  * targetId 目标id
  * obj 目标对象
  */
 const appendNodeById = (list, targetId, obj) => {
    
    
   if (!list) return
   list.forEach(item => {
    
    
     if (item.id === targetId) {
    
    
       item.children ? item.children.push(obj) : item['children'] = [obj];
     } else {
    
    
       if (item.children && Array.isArray(item.children) && item.children.length) {
    
    
         appendNodeById(item.children, targetId, obj)
       }
     }
   })
 }

2. 编辑

/**
  * 树形修改事件
  * list 树形列表数据
  * targetId 目标id
  * obj 目标对象
  */
 const updateNodeById = (list, targetId, obj) => {
    
    
   if (!list) return
   list.forEach((item, index) => {
    
    
     if (item.id === targetId) {
    
    
       list.splice(index, 1, obj)
       return
     } else {
    
    
       if (item.children && Array.isArray(item.children) && item.children.length) {
    
    
         updateNodeById(item.children, targetId, obj)
       }
     }
   })
 }

3. 删除

/**
  * 树形删除事件
  * 根据目标id删除指定节点
  * list 树形列表数据
  * targetId 目标id
  */
 const deleteNodeById = (list, targetId) => {
    
    
   if (!list) return
   list.forEach((item, index) => {
    
    
     if (item.id === targetId) {
    
    
       list.splice(index, 1)
       return
     } else {
    
    
       if (item.children && Array.isArray(item.children) && item.children.length) {
    
    
         deleteNodeById(item.children, targetId)
       }
     }
   })
 }

4. 查找

/**
  * 树形查找事件
  * 根据目标id查找指定节点
  * list 树形列表数据
  * targetId 目标id
  */
 const selectNodeById = (list, targetId) => {
    
    
   if (!list) return;
   let nodeTree = null;
   for (let i = 0; i < list.length; i++) {
    
    
     if (nodeTree !== null) break
     let node = list[i];
     if (node.id === targetId) {
    
    
       nodeTree = node;
       break;
     } else {
    
    
       if (item.children && Array.isArray(node.children) && node.children.length) {
    
    
         nodeTree = selectNodeById(node.children, targetId);
       }
     }
   }
   return nodeTree
 }

5. 通过父节点找到子节点

  treeFindPath(tree, func, field = "", path = []) {
    
    
      if (!tree) return [];
      for (const data of tree) {
    
    
        field === "" ? path.push(data) : path.push(data[field]);
        if (func(data)) return path;
        if (data.children) {
    
    
          const findChildren = this.treeFindPath(data.children, func, field, path)
          if (findChildren.length) return findChildren;
        }
        path.pop()
      }
      return []
    },

猜你喜欢

转载自blog.csdn.net/weixin_44244924/article/details/130311968
今日推荐