vue实现左方导航栏,要求:1.父节点点击后下拉出子节点,并且父节点带有左图标,右边图标是上下标志以及自身颜色变蓝。2.子节点有多个,鼠标经过的时候,只有字体变蓝,点击后整个小li变浅蓝并且自身颜色变蓝,。3.点击其他父节点后,当前父节点出现1,2情况,其他父节点折叠起来
时间: 2023-10-15 21:08:08 浏览: 83
可以参考以下代码实现:
```
<template>
<div class="nav-container">
<ul class="nav-list">
<li v-for="item in navData" :key="item.id" :class="{active: item.active}">
<div class="parent" @click="toggle(item.id)">
<span class="iconfont" :class="{icon-active: item.active}">
{{ item.icon }}
</span>
<span>{{ item.name }}</span>
<span class="iconfont arrow" :class="{down: item.active, up: !item.active}">

</span>
</div>
<ul class="child" v-show="item.active">
<li v-for="(child, index) in item.children" :key="index" @click="select(item.id, index)" :class="{active: child.active}">
<span>{{ child.name }}</span>
</li>
</ul>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
navData: [
{
id: 1,
name: '父节点1',
icon: '',
active: false,
children: [
{ id: 11, name: '子节点1' },
{ id: 12, name: '子节点2' },
{ id: 13, name: '子节点3' },
]
},
{
id: 2,
name: '父节点2',
icon: '',
active: false,
children: [
{ id: 21, name: '子节点1' },
{ id: 22, name: '子节点2' },
{ id: 23, name: '子节点3' },
]
},
{
id: 3,
name: '父节点3',
icon: '',
active: false,
children: [
{ id: 31, name: '子节点1' },
{ id: 32, name: '子节点2' },
{ id: 33, name: '子节点3' },
]
},
]
}
},
methods: {
toggle(id) {
this.navData.forEach(item => {
if (item.id === id) {
item.active = !item.active;
} else {
item.active = false;
}
});
},
select(parentId, childIndex) {
this.navData.forEach(item => {
if (item.id === parentId) {
item.children.forEach((child, index) => {
if (index === childIndex) {
child.active = true;
} else {
child.active = false;
}
});
item.active = true;
} else {
item.active = false;
item.children.forEach(child => {
child.active = false;
});
}
});
}
}
}
</script>
<style>
.nav-container {
width: 200px;
}
.nav-list {
list-style: none;
padding: 0;
margin: 0;
}
.parent {
display: flex;
align-items: center;
padding: 10px 20px;
cursor: pointer;
}
.parent:hover {
background-color: #f1f1f1;
}
.parent .iconfont {
font-size: 16px;
margin-right: 10px;
color: #666;
}
.parent .icon-active {
color: blue;
}
.parent .arrow {
margin-left: auto;
}
.parent .down {
transform: rotate(0deg);
}
.parent .up {
transform: rotate(-180deg);
}
.child {
list-style: none;
padding: 0;
margin: 0;
}
.child li {
display: flex;
align-items: center;
padding: 10px 40px;
cursor: pointer;
}
.child li:hover {
background-color: #f1f1f1;
}
.child li.active {
background-color: #e1e1e1;
}
.child li span {
color: #666;
}
.child li.active span {
color: blue;
}
</style>
```
以上代码实现了左侧导航栏的功能,包括父节点的展开和折叠,子节点的选中和颜色变化,以及点击其他父节点后当前父节点的展开和其他父节点的折叠。需要注意的是,可以根据自己的需求修改样式和数据结构。
阅读全文