在页面未刷新之前,每个导航都可以点击跳转到对应的页面并且跳转路径一致,但是一旦刷新,当前高亮的导航选项和页面以及跳转路径就不一样了。
问题展示:
🌹第一种解决方式
打开elementUI官网可以看到有一个select事件,如下图:
首先可以在代码中绑定一个事件函数,在函数方法中传入index参数,并且使用localStorage存储index,接着在生命周期函数created中把index赋值
代码如下:
<template>
<div>
<!-- 导航 -->
<el-menu
:default-active="activeIndex"
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b"
router
@select="selectMenu"
>
<el-menu-item index="/">首页 </el-menu-item>
<el-menu-item index="/about">关于 </el-menu-item>
<el-menu-item index="/personal">个人中心 </el-menu-item>
</el-menu>
<!-- 出口 -->
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "DianshangLayout",
data() {
return {
activeIndex: "/",
};
},
methods: {
//1、定义函数,绑定到@select
selectMenu(index, path) {
console.log(index, path);
//存储index的值
localStorage.setItem("index", index);
},
},
created() {
//生命周期获取index并赋值
let index = localStorage.getItem("index");
if (index) {
this.activeIndex = index;
}
},
};
</script>
解决之后效果如下:
🌹第二种解决方式
直接在el-menu给default-active绑定$route.path就可以快速实现 :default-active="$route.path"
代码如下:
<template>
<div>
<!-- 导航 -->
<el-menu
:default-active="$route.path"
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b"
router
>
<el-menu-item index="/">首页 </el-menu-item>
<el-menu-item index="/about">关于 </el-menu-item>
<el-menu-item index="/personal">个人中心 </el-menu-item>
</el-menu>
<!-- 出口 -->
<router-view></router-view>
</div>
</template>