使用element-ui的el-menu刷新之后保持选中状态

305 阅读1分钟

代码部分

1、handle[Select函数]官网示例给出的是2个参数key和keyPath,分别打印出来后是一样的都是当前的路径。保留一个就可以,然后把路径放在sessionStorage中。
2、在[vue生命周期]mounted函数中把这个当前路径赋值给 activeIndex 即赋值给了 default-active 参数。第一次访问的时候sessionStorage是空的,所以要加入默认的路径。
3、点击链接是可以完美做到刷新后会保持选中状态,但是当我们手动输入路由的时候,页面会跳转但是css样式不会改变。所有加上watch监听属性来监听activeIndex。当输入的路由和当前的路由不一样的时候。把当前的路由赋值给activeIndex。

`1.  <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect"
1.  active-text-color="#4985ED">
1.  <el-menu-item index="1">
1.  <router-link to="/" class="about">首页</router-link>
1.  </el-menu-item>
1.  <el-menu-item index="2">
1.  <router-link to="/about" class="about">API接口</router-link>
1.  </el-menu-item>
1.  <el-menu-item index="3">
1.  <router-link to="/help" class="about">帮助支持</router-link>
1.  </el-menu-item>
1.  <el-menu-item index="4">
1.  <router-link to="/aboutUs" class="about">关于我们</router-link>
1.  </el-menu-item>
1.  </el-menu>
1.
1.  <script>
1.  export default {
1.  data() {
1.  return {
1.  activeIndex: '1',
1.  };
1.  },
1.  mounted() {
1.  this.activeIndex = sessionStorage.getItem('keyPath') || '1';
1.  },
1.  watch: {
1.  activeIndex(newValue) {
1.  // if (newValur != this.$route.path) {
1.  // this.activeIndex = this.$route.path;
1.  // }
1.  // 如果使用 v-for 循环 可以取消上面注释
1.  console.log(newValue);
1.  }
1.  },
1.  methods: {
1.  handleSelect(keyPath) {
1.  sessionStorage.setItem('keyPath', keyPath);
1.  }
1.  }
1.  }
1.  </script>`