如果您想要实现在刷新页面后自动打开当前菜单,可以考虑以下两种方法:

  1. 利用 localStorage 或 sessionStorage 存储当前菜单的激活项

在菜单项被点击时,将当前激活的菜单项的 index 存储到 localStorage 或 sessionStorage 中。在页面刷新时,从 localStorage 或 sessionStorage 中读取存储的 index,然后通过 $refs.menu.setActiveItem 方法将对应的菜单项激活。例如:

// 在菜单项被点击时
handleMenuClick(index) {
  localStorage.setItem('activeMenuIndex', index);
}

// 在页面刷新时
mounted() {
  const activeMenuIndex = localStorage.getItem('activeMenuIndex');
  if (activeMenuIndex) {
    this.$refs.menu.setActiveItem(activeMenuIndex);
  }
}
  1. 利用路由守卫设置菜单的激活项

在路由守卫中,根据当前路由的路径设置菜单的激活项。在菜单项被点击时,通过 $router.push 方法跳转到对应的路由。例如:

// 在路由配置中设置菜单的 index
const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    meta: { menuIndex: '1' } // 设置菜单的 index
  },
  // ...
]

// 在路由守卫中设置菜单的激活项
router.beforeEach((to, from, next) => {
  const menuIndex = to.meta.menuIndex;
  if (menuIndex) {
    vm.$nextTick(() => {
      vm.$refs.menu.setActiveIndex(menuIndex);
    });
  }
  next();
});

// 在菜单项被点击时跳转到对应路由
handleMenuClick(index) {
  const path = this.$router.options.routes.find(route => route.meta.menuIndex === index)?.path;
  if (path) {
    this.$router.push(path);
  }
}

这两种方法都需要在页面刷新后重新设置菜单的激活项,以实现自动打开当前菜单。

vue el-menu刷新页面菜单不能自动打开

原文地址: https://www.cveoy.top/t/topic/bgla 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录