模板
代碼如下
html
<template> <div class="header"> <ul> <!-- 循環數據在點擊調用changeli方法時將當前索引和本條數據傳進去,並使用當前數據show的bool值添加或移除樣式 --> <li :class="[{active:item.show}]" @click="changeli(index,item)" v-for="(item,index) in headerData"> <!-- 在這里打印出boll值方便查看 --> {{item.name}}{{item.show}} <!-- 判斷當前這條數據的bool值如果是true就打開二級菜單,如果是false就關閉二級菜單 --> <ul v-show="item.show"> <!-- 循環二級菜單數據並使用.stop阻止冒泡 --> <li v-for="(a,index) in item.list" v-on:click.stop="doThis(index)">{{a}}</li> </ul> </li> </ul> </div> </template>
js
export default { data() { return { headerData: [{ name: '導航1', list: ['子集', '子集', '子集', '子集', '子集'], show: false }, { name: '導航2', list: ['子集', '子集', '子集', '子集', '子集'], show: false }, { name: '導航3', list: ['子集', '子集', '子集', '子集', '子集'], show: false }, { name: '導航4', list: ['子集', '子集', '子集', '子集', '子集'], show: false }, { name: '導航5', list: ['子集', '子集', '子集', '子集', '子集'], show: false }] } }, methods: { changeli: function(ind, item) { // 先循環數據中的show將其全部置為false,此時模板里的v-if判斷生效關閉全部二級菜單,並移除樣式 this.headerData.forEach(i => { // 判斷如果數據中的headerData[i]的show屬性不等於當前數據的show屬性那么headerData[i]等於false if (i.show !== this.headerData[ind].show) { i.show = false; }; }); // 取反(true或false) item.show = !item.show; console.log(item.name) }, doThis: function(index) { alert(index) } } }
css
.header { width: 20%; background-color: #ff5722; color: #ffffff; >ul { width: 100%; @include clearfix; >li { width: 100%; border: 1px solid #ffffff; cursor: pointer; // float: left; color: 20px; text-align: center; line-height: 60px; &:hover { background-color: #ff9800; } >ul { width: 100%; background: red; li{ &:hover{ background: #c31111; } } } } .active { background-color: #ff9800; } } }