代码部分
1、handleSelect函数官网示例给出的是2个参数key和keyPath,分别打印出来后是一样的都是当前的路径。保留一个就可以,然后把路径放在sessionStorage中。
2、在vue生命周期mounted函数中把这个当前路径赋值给 activeIndex 即赋值给了 default-active 参数。第一次访问的时候sessionStorage是空的,所以要加入默认的路径。
3、点击链接是可以完美做到刷新后会保持选中状态,但是当我们手动输入路由的时候,页面会跳转但是css样式不会改变。所有加上watch监听属性来监听activeIndex。当输入的路由和当前的路由不一样的时候。把当前的路由赋值给activeIndex。
原文链接:https://blog.csdn.net/qq_28262385/article/details/126003201
<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect"
active-text-color="#4985ED">
<el-menu-item index="1">
<router-link to="/" class="about">首页</router-link>
</el-menu-item>
<el-menu-item index="2">
<router-link to="/about" class="about">API接口</router-link>
</el-menu-item>
<el-menu-item index="3">
<router-link to="/help" class="about">帮助支持</router-link>
</el-menu-item>
<el-menu-item index="4">
<router-link to="/aboutUs" class="about">关于我们</router-link>
</el-menu-item>
</el-menu>
<script>
export default {
data() {
return {
activeIndex: '1',
};
},
mounted() {
this.activeIndex = sessionStorage.getItem('keyPath') || '1';
},
watch: {
activeIndex(newValue) {
// if (newValur != this.$route.path) {
// this.activeIndex = this.$route.path;
// }
// 如果使用 v-for 循环 可以取消上面注释
console.log(newValue);
}
},
methods: {
handleSelect(keyPath) {
sessionStorage.setItem('keyPath', keyPath);
}
}
}
</script>