element 联级菜单怎么根据一个 value去查询其他的?

比如根据最后一级的value: 'kekong' 去查出来它的父级和祖先级 给拼成: 指南=>设计原则=>可控

options: [{
  value: 'zhinan',
  label: '指南',
  children: [{
    value: 'shejiyuanze',
    label: '设计原则',
    children: [
      {
      value: 'yizhi',
      label: '一致'
    }, 
      {
      value: 'fankui',
      label: '反馈'
    }, 
      {
      value: 'xiaolv',
      label: '效率'
    }, 
      {
      value: 'kekong',
      label: '可控'
    }]
  }]
}]
阅读 2.4k
2 个回答

不清楚你的查是什么意思,是click还是filter
element tree提供的方法大部分都提供了Node的返回,你自己查parent查到null为止不就行了么。

以下为操作原始数据的方法,不过说实话这种方法和element tree一起用我没想到是怎么的需求。

let options = [{
    value: 'zhinan',
    label: '指南',
    children: [{
        value: 'shejiyuanze',
        label: '设计原则',
        children: [{
                value: 'yizhi',
                label: '一致'
            },
            {
                value: 'fankui',
                label: '反馈'
            },
            {
                value: 'xiaolv',
                label: '效率'
            },
            {
                value: 'kekong',
                label: '可控'
            }
        ]
    }, {
        value: 'shejiyuanze2',
        label: '设计原则2',
        children: [{
            value: 'yizhi2',
            label: '一致2'
        }]
    }]
}, {
    value: 'zhinan2',
    label: '指南2',
}]

function findOption(parents, val = '', node = []) {
    for (let p of parents) {
        if (p.value === val) {
            node.push(p.label)
            return node;
        } else {
            if (p.children && p.children.length) {
                node.push(p.label);
                let same = findOption(p.children, val, node);
                if (!same) {
                    node.splice(node.length - 1, 1);
                } else {
                    return node;
                }
            }
        }
    }
}

let node = findOption(options, 'kekong');
console.log(node.join(' => '))

不需要查询其他的吧,本身element-ui的级联选择器给你返回的是一个数组
如果你选择了 指南 设计 原则 可控 就会得到
['zhinan', 'shejiyuanze', 'kekong' ]
两种简单做法 前置
1: 把 value 也变为 汉字
2: 开始之前设置一个 对象

const fontMap = {
    zhinan: '指南',
    shejiyuanze: '原则'
    ...
}

然后 在数组中根据 对象 key 得到 对象 value
第三种 在数组中 你每次 都使用find

//  这个你要判断有多长
const one = options.find(x => x.label === value[0])
...

第四种 根据现有数据结构 去生成一个 树,每个树节点自带 parent, 然后你先找到你要的节点,根据parent不为空
来while循环

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题