描述:
后台返回的数据采用v-for
渲染到<li>
中,点击对应一级标签显示对应二级内容。
数据格式:
test: [
{ id: 1,
name: '1',
child: [
{ id: 11, name: '11' },
{ id: 12, name: '12' },
{ id: 13, name: '13' },
{ id: 14, name: '14' }
]
},
{ id: 2,
name: '2',
child: [
{ id: 21, name: '21' },
{ id: 22, name: '22' },
{ id: 23, name: '23' },
{ id: 24, name: '24' }
]
}
]
思路
遍历父级,给父级绑定点击事件,点击将id存入data;
判断data中所存id是否为父级列表id,是的话显示子级。
代码
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test</title>
<script type="text/javascript" src="vue.js"></script>
<!-- :class="activeId==fartherItem.id ? 'activeStyle': 'commonStyle' " -->
<style type="text/css">
.activeStyle {
background: #baf
}
.commonStyle {
background: #bfa;
borderBottom: 1px solid #eee;
}
</style>
</head>
<body>
<div id="vue_app" style="line-height: 50px;">
<ul style="float: left;width: 100px;position: absolute;">
<li
v-for="fartherItem in test"
@click="toggle(fartherItem.id)"
:class="activeId==fartherItem.id ? 'activeStyle' : ''">
{{fartherItem.name}}
<ul style="position: absolute; width: 100px; top: 0; right: -120px" v-show="activeId==fartherItem.id ">
<li v-for="item in fartherItem.child">
{{item.name}}
</li>
</ul>
</li>
</ul>
</div>
<script>
app_all=new Vue({
el: "#vue_app",
data: {
activeId: '11111',
test: [
{ id: 1,
name: '1',
child: [{ id: 11, name: '11' }, { id: 12, name: '12' }, { id: 13, name: '13' }, { id: 14, name: '14' }]
},
{ id: 2,
name: '2',
child: [{ id: 21, name: '21' }, { id: 22, name: '22' }, { id: 23, name: '23' }, { id: 24, name: '24' }]
}
]
},
methods: {
toggle(id) {
this.activeId = id
console.log(this.activeId)
}
}
})
</script>
</body>
</html>