在写vue项目头部导航时,随便点击头部导航后,页面刷新,高亮状态显示在回到第一个,而不是在保持在刚刚点击的地方
<template>
<div class="list">
<ul>
<li :class="tableIndex == index ? 'activeATable' : ''"
v-for="(item, index) in headerList" :key="index"
@click="clickList(index, item.path)">
<p>{{ item.name }}</p>
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue';
//路由引入
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
//首页导航
const headerList = [
{ path: '/', name: '首页' },
{ path: '/demand', name: '需求大厅' },
{ path: '/service', name: '找服务商' },
{ path: '/resource', name: '资源商城' },
{ path: '/recruit', name: '招募大厅' },
{ path: '/advertisement', name: '广告消息' },
{ path: '/businessCard', name: '群名片' }
]
let tableIndex = ref("0")
const clickList = (index, path) => {
tableIndex.value = index
router.push(path)
}
</script>
<style lang="less" scoped>
.list {
ul {
max-width: 1296px;
height: 100px;
margin-left: 60px;
list-style: none;
display: flex;
align-items: center;
text-align: center;
}
li {
width: 100px;
height: 100px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
}
//高亮
.activeATable {
color: #2EB135;
}
</style>
代码写到这里的时候,表面没有任何的问题 但是在页面刷新后会出现高点丢失的问题 ,下面的解决问题的代码
<script setup>
import { ref } from 'vue';
//路由引入
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
//首页导航
const headerList = [
{ path: '/', name: '首页' },
{ path: '/a', name: '需求大厅' },
{ path: '/b', name: '找服务商' },
{ path: '/c', name: '资源商城' },
{ path: '/d', name: '招募大厅' },
{ path: '/e', name: '广告消息' },
{ path: '/f', name: '群名片' }
]
//导航栏高亮显示丢失问题解决方案
router.beforeEach((to, from, next) => {
console.log('当前页面的路由路径:', to.fullPath);
if (to.fullPath == '/a') {
tableIndex.value = '1'
} else if (to.fullPath == '/b') {
tableIndex.value = '2'
} else if (to.fullPath == '/c') {
tableIndex.value = '3'
} else if (to.fullPath == '/d') {
tableIndex.value = '4'
} else if (to.fullPath == '/e') {
tableIndex.value = '5'
} else if (to.fullPath == '/f') {
tableIndex.value = '6'
} else if (to.fullPath == '/') {
tableIndex.value = '0'
} else {
tableIndex.value = '999'
}
next();
});
let tableIndex = ref("0")
const clickList = (index, path) => {
tableIndex.value = index
router.push(path)
}
</script>