vue2写法
<template>
<div class="header">
<ul>
<!-- 循环数据在点击调用changeli方法时将当前索引和本条数据传进去,并使用当前数据show的bool值添加或移除样式 -->
<li :class="[{ active: item.show }]" @click="changeli(index, item)" v-for="(item, index) in global">
<!-- 在这里打印出boll值方便查看 -->
{{ item.name }}{{ item.show }}
<!-- {{ item.name }} -->
<!-- 判断当前这条数据的bool值如果是true就打开二级菜单,如果是false就关闭二级菜单 -->
<ul v-show="item.show">
<!-- 循环二级菜单数据并使用.stop阻止冒泡 -->
<li v-for="(a, index) in item.children" v-on:click.stop="doThis(index)">{{ a.name }}</li>
</ul>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
global: [
{
name: '我的',
children: [
{ name: '订单' },
{ name: '个人中心' }
],
show: false
},
{
name: '设置',
show: false
},
{
name: '消息',
children: [
{
name: '私信',
},
{
name: '系统设置',
},
],
show: false
},
{
name: '版本',
show: false
},
{
name: '退出',
show: false
}
]
}
},
methods: {
changeli: function (ind, item) {
// 先循环数据中的show将其全部置为false,此时模板里的v-if判断生效关闭全部二级菜单,并移除样式
this.global.forEach(i => {
console.log(i.show)
// 判断如果数据中的headerData[i]的show属性不等于当前数据的show属性那么headerData[i]等于false
if (i.show !== this.global[ind].show) {
i.show = false;
};
});
// 取反(true或false)
item.show = !item.show;
console.log(item.name)
},
doThis: function (index) {
alert(index)
}
}
}
</script>
vue3写法
<template>
<div class="menu-item" v-for="(item, index) in data.global" :key="index">
<div class="menu-item-children">
<router-link to="" class="d-flex align-items-center" @click="handleClick(item, index)"
:class="item.name == names ? 'bg' : ''">
<span v-if="menuOpen">{{ item.name }}</span>
<down-outlined class="triangle" v-if="item.children && menuOpen" :class="item.show ? 'rotate' : ''" />
</router-link>
<div v-if="item.show">
<router-link to="" v-for="(it, ind) in item.children" :key="ind" class="d-flex align-items-center">
<span>{{ it.name }}</span>
</router-link>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { global } from './nav';
import { UpOutlined, DownOutlined } from '@ant-design/icons-vue';
import { storeToRefs } from 'pinia';
import { reactive, ref } from 'vue'
import { cloneDeep } from 'lodash';
import { $api } from '@/api';
//接收父组件传来的值
defineProps<{ menuOpen: boolean, names: string }>();
//克隆global数组数据
const data: { global: any[] } = reactive({
global: []
});
data.global = cloneDeep(global);
//向父组件传递name值
const emits = defineEmits(['getNames']);
const handleClick = (item, ind) => {
emits('getNames', item.name)
data.global.forEach(i => {
if (i.show !== data.global[ind].show) {
i.show = false;
};
});
item.show = !item.show;
}
</script>
|