采用递归方式遍历比对名称,并记录层次
data(){
return{
organizeIndex: 0, //记录层次
treeData: [
id: 0,
name: '中国',
children: [
{
id: 2,
name: '安徽省‘,
children: [
id: 3,
name: '阜阳市',
children:[.............]
]
},
{
id: 4,
name: '浙江省‘,
children: [
id: 5,
name: '杭州市',
children:[.............]
]
}
]
]
}
}
created: {
this.listArr(this.treeData, '杭州市', 0);
alert(this.organizeIndex)
},
methods: {
/**
* 遍历树形结构,判断是在第几层级
* @param data
* @param name
* @param int
*/
listArr: function (data, name, int) {
if (data.Name == name) {
this.organizeIndex = int
return true;
}
if (!!!data.Children) {
return false;
}
for (let i = 0; i < data.Children.length; i++) {
if (this.listArr(data.Children[i], name, int + 1)) {
return true;
}
}
return false;
},
}