vue3路由跳转后激活菜单匹配不上的问题
出现原因: 路由跳转后继续运行了onMounted
钩子函数,导致我们保存的激活菜单被重制了。
解决办法:
1.将激活路径保存在store中,onMounted函数中将store中保存的激活菜单取出;
2.将激活路径保存在localStorage中,onMounted函数中将localStorage中保存的激活菜单取出;
3.onMounted函数中获取页面的路由name,再赋值给激活菜单(需要name和激活菜单字段是一致)
以下为第三种办法的实例:
<template>
<div id="alarmList" class="menuList">
<div class="menuNumberContainer">
<div
v-for="item in menuNumber"
:key="item.key"
class="card"
:class="activeMenu == item.key ? 'active-menu-style' : ''" //此处做了一个激活样式 activeMenu
@click="changePage(item)"
>
<img :src="item.img" alt="" />
<div class="menuName">{{ item.name }}</div>
</div>
</div>
<router-view v-slot="{ Component, route }" :key="$route.fullPath">
<!-- <transition appear name="fade-transform" mode="out-in"> -->
<component :is="Component" :key="route.path" @update-station="updateStation" />
<!-- </transition> -->
</router-view>
</div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, nextTick, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const activeMenu = ref<string>('homePage'); // 进入页面默认 homePage 页面
const menuNumber = reactive([
{key: 'homePage',},
{key: 'mainWiringDiagram',},
{key: 'deviceMonitor',},
{key: 'faultAlarm',},
{key: 'curveReport',},
]);
const changePage = (item: any) => {
// 点击按钮后进行页面跳转
// 记录当前点击的按钮来匹配激活的菜单,!!!!但是!!!并没有生效
// activeMenu.value = item.key;
// 跳转路由
router.push(item.key);
};
//路由跳转后会重新运行这个钩子函数
onMounted(() => {
// 应该采用这段
// router.currentRoute.value.name 查询当前的路由名称,将路由名称赋值给 activeMenu (注意:需要路由名称和activeMenu是一样的字段才行)
activeMenu.value = router.currentRoute.value.name ? router.currentRoute.value.name : 'homePage';
});
</script>