vue2 导航栏刷新页面,之前选中的文字依然高亮 代码如下,没有使用element_ui中的菜单栏
<template>
<nav class="navbar navbar-expand-lg bg-body-tertiary" style="margin: 0 auto;">
<div class="container-fluid">
<div>
<ul class="navbar-nav1">
<li
class="nav_li"
v-for="item in navItems"
:key="item.index"
:class="{ active: currentIndex === item.index }"
@click="handleNavClick(item, item.index)"
>
{{ item.text }}
<div v-if="item.showPopup" class="popup">
<ul style="width: auto;">
<li
v-for="(child, index) in item.child"
:key="index"
:class="{ hovered: hoveredChild === child.name }"
@click="handleNavClick1(child)"
@mouseover="hoverChild(child.name)"
@mouseout="unhoverChild(child.name)"
>
{{ child.name }}
</li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</nav>
</template>
<script>
export default {
data() {
return {
hoverIndex: null,
seen: true,
currentIndex: "1", // 默认选中第一个
navItems: [
{ text: '首页', router: "Index", index: "1" },
{
text: '关于我们',
index: "2",
child: [
{
name: '企业简介',
show: false,
router: "gongsijianjie",
},
{
name: '企业文化',
show: false,
router: "aboutus",
},
],
showPopup: false,
},
{
text:'产品中心',
index: "3",
child: [
{
name: '管理系统',
show: false,
router: "mibxitong",
},
{
name:'小程序',
show: false,
router: "smallapp",
},
{
name: '机器人',
show: false,
router: "softwareproduct",
},
],
showPopup: false,
},
{
text: '合作伙伴',
router: "zhengqihezuo",
index: "4",
},
{
text: '联系我们',
router: "cityle1",
index: "5",
},
],
itemTooltip: "这是一个工具提示",
};
},
created() {
const currentRouterName = this.$route.name; // 假设你的路由配置中有 name 属性
const index = this.findIndexByRouter(currentRouterName);
console.log(index, "index"); // 输出找到的 index 或 null
this.currentIndex = index;
},
watch: {
},
methods: {
findIndexByRouter(routerName) {
for (let item of this.navItems) {
if (item.router === routerName) {
return item.index;
}
if (item.child && Array.isArray(item.child)) {
for (let child of item.child) {
if (child.router === routerName) {
return item.index;
}
}
}
}
return null; // 如果没有找到匹配的路由,返回 null 或其他默认值
},
hoverChild(name) {
// console.log(name, "name");
this.hoveredChild = name;
},
unhoverChild() {
this.hoveredChild = null;
},
handleNavClick(item, index) {
console.log(item, "item");
this.currentIndex = index; // 更新当前选中项
console.log(this.currentIndex);
// localStorage.setItem("currentIndex", this.currentIndex);
// console.log(localStorage.getItem("currentIndex"), "currentIndex");
if (item.child) {
// 如果当前项有子项,则切换弹出框的显示状态
item.showPopup = !item.showPopup;
}
this.$router.push({ name: item.router });
},
handleNavClick1(item, index) {
// console.log(item, "item1");
this.$router.push({ name: item.router });
},
menuitem(e, a1) {
this.array = e.detail;
this.hoverIndex = a1;
// console.log(this.hoverIndex,'this.ad')
},
showItemInfo(item) {
console.log(item, "item");
this.showTooltipContent = true;
this.displayedInfo = item.info;
this.title = item.label;
// this.activeIndex = item.label; // 如果需要高亮显示当前菜单项
},
};
</script>