如何用v-if在HTML列表中按tid长度分级展示(7位一级、10位二级)
Vue树形列表二级节点不显示问题修复
问题原因
你当前的代码逻辑存在错误:遍历每条数据时,在同一个item里同时判断tid长度为7和10——但每条数据的tid只能是一种长度,所以二级节点的v-if永远不会触发,自然看不到二级节点。
解决方法一:模板内直接筛选二级节点(简单场景适用)
修改模板,先循环所有一级节点,再为每个一级节点筛选出对应前缀的二级节点:
<template> <div class="css-treeview"> <!-- 只遍历一级节点(tid长度为7) --> <template v-for="parentItem in treelist.filter(item => item.t.length === 7)" :key="parentItem.t"> <ul> <li> <input type="checkbox" :id="`item-${parentItem.t}`" /> <label :for="`item-${parentItem.t}`">{{ parentItem.mAcName }} --- {{ parentItem.mName }}</label> <!-- 筛选当前一级节点对应的二级节点:tid以一级节点tid开头且长度为10 --> <ul v-if="treelist.some(child => child.t.startsWith(parentItem.t) && child.t.length === 10)"> <template v-for="childItem in treelist.filter(child => child.t.startsWith(parentItem.t) && child.t.length === 10)" :key="childItem.t"> <li> <input type="checkbox" :id="`item-${childItem.t}`" /> <label :for="`item-${childItem.t}`">{{ childItem.mAcName }} --- {{ childItem.mName }}</label> </li> </template> </ul> </li> </ul> </template> </div> </template>
注意点:
- 用
filter过滤出一级节点,避免无效遍历 - 用
startsWith匹配二级节点的归属关系(符合你示例中8000001对应8000001000的规则) - 给checkbox的
id和for绑定动态值,避免重复id导致交互异常
解决方法二:提前处理为树形结构(推荐,性能更优)
在计算属性里把扁平数组转换成树形结构,模板逻辑会更清晰,也减少重复遍历数组的开销:
<template> <div class="css-treeview"> <template v-for="parent in treeData" :key="parent.t"> <ul> <li> <input type="checkbox" :id="`item-${parent.t}`" /> <label :for="`item-${parent.t}`">{{ parent.mAcName }} --- {{ parent.mName }}</label> <ul v-if="parent.children.length"> <template v-for="child in parent.children" :key="child.t"> <li> <input type="checkbox" :id="`item-${child.t}`" /> <label :for="`item-${child.t}`">{{ child.mAcName }} --- {{ child.mName }}</label> </li> </template> </ul> </li> </ul> </template> </div> </template> <script> export default { computed: { treeData() { // 筛选所有一级节点 const parentNodes = this.treelist.filter(item => item.t.length === 7); // 为每个一级节点匹配对应的二级节点 return parentNodes.map(parent => ({ ...parent, children: this.treelist.filter(child => child.t.length === 10 && child.t.startsWith(parent.t) ) })); } } } </script>
优势:
- 只需要遍历数组两次,比模板内多次
filter性能更好 - 模板逻辑更简洁,无需在模板里写复杂的筛选条件
内容的提问来源于stack exchange,提问作者Meow
相关产品推荐
相关产品推荐

