原创,转载请附加转载来源.
Element UI 的Cascader是很好的层级控件,https://element.eleme.cn/#/zh-CN/component/cascader
很多时候当我们只知道最后一个节点值,然后需要根据子节点一步一步获取完整的父节点的值,
直接代码吧:
/**
* Created by kun on 2020/7/17
* @param {object} cascader - element ui cascader options
* @param {number} id - last child node value
* @returns {Array} - full value for cascader show
*
*/
export function getCascaderFullValue(cascader, id) {
let cascaderFullValue = [id];
_getParentId(cascaderFullValue, cascader,cascader, id);
return cascaderFullValue;
/**
*
* @param {Array} cascaderFullValue value for return
* @param {Array} cascader value for loop
* @param {Array} _cascader value of original
* @param {number} _id value of bottom item
*/
function _getParentId(cascaderFullValue, cascader, _cascader, _id) {
if (!Array.isArray(cascader)) return;
for (let cascaderItem of cascader) {
if (!Array.isArray(cascaderItem.children)) continue;
let index = cascaderItem.children.findIndex(item => item.value === _id);
if (index >= 0) {
cascaderFullValue.unshift(cascaderItem.value);
if(_cascader.findIndex(item => item.value === cascaderItem.value) < 0) //is original item
_getParentId(cascaderFullValue, _cascader, _cascader,cascaderItem.value);
} else {
_getParentId(cascaderFullValue, cascaderItem.children, _cascader,_id);
}
}
}
}
测试数据源json:
{
"data":[
{
"value":7,
"label":"初级会计师22",
"children":[
{
"value":11,
"label":"初级会计实务",
"children":[
{
"value":13,
"label":"初级会计实务试卷模块",
"children":null
}
]
}
]
},
{
"value":6,
"label":"审计师",
"children":[
{
"value":12,
"label":"审计与考核",
"children":[
{
"value":14,
"label":"审计与考核模块!!",
"children":null
}
]
},
{
"value":10,
"label":"审计理论",
"children":[
{
"value":15,
"label":"审计模块!222!",
"children":null
}
]
}
]
}
]
}
假设已知后台拿到最后节点值为14,调用
console.log(this.cascader); //json 数据源
const result = getCascaderFullValue(this.cascader,14);
console.log(result);//[6, 12, 14]
效果图: