根据id获取到对应的label并修改其值

const dataSource = ref([
  {
    id: 1,
    label: 'Level one 1',
    children: [
      {
        id: 4,
        label: 'Level two 1-1',
        children: [
          {
            id: 9,
            label: 'Level three 1-1-1',
          },
          {
            id: 10,
            label: 'Level three 1-1-2',
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: 'Level one 2',
    children: [
      {
        id: 5,
        label: 'Level two 2-1',
      },
      {
        id: 6,
        label: 'Level two 2-2',
      },
    ],
  },
  {
    id: 3,
    label: 'Level one 3',
    children: [
      {
        id: 7,
        label: 'Level two 3-1',
      },
      {
        id: 8,
        label: 'Level two 3-2',
      },
    ],
  },
]);

 根据id获取到对应的label并修改其值:

function findDataById(tree, id) {
  let result = null;
  function traverse(node) {
    if (node.id === id) {
      result = node;
      return;
    }
    if (node.children && node.children.length > 0) {
      node.children.forEach((child) => {
        traverse(child);
      });
    }
  }
  tree.forEach((node) => {
    traverse(node);
  });
  return result;
}

onMounted(() => {
  const id = 9; // 要查找的id
  const data = findDataById(dataSource.value, id);
  if (data) {
    console.log('原始label:', data.label);
    // 修改label为新的值
    data.label = '新的 label 值';
    console.log('修改后的label:', data.label);
  }
});

获取数组中所有的id:

function findIds(tree) {
  const ids = [];
  function traverse(node) {
    ids.push(node.id);
    if (node.children && node.children.length > 0) {
      node.children.forEach((child) => {
        traverse(child);
      });
    }
  }
  tree.forEach((node) => {
    traverse(node);
  });
  return ids;
}

onMounted(() => {
  const proxyIds = findIds(dataSource.value);
  const treeIds = findIds(dataSource.value);
  const matchedIds = proxyIds.filter((id) => treeIds.includes(id));
  console.log(matchedIds,"数组中所有的id");
});

你可能感兴趣的:(前端,javascript,vue.js,Tree,el-tree)