index.js 2.44 KB
import menuData from "@/router/modules/menu";
import { mapState } from "vuex";
import createMenu from "./components/menuItem";

export default {
  data() {
    return {
      selectData: [],
      openKeys: [],
    };
  },
  computed: {
    ...mapState({
      menuStack: (state) => state.common.menuStack,
    }),
    // 访问下级页的时候记录当前根菜单高亮
    currentSelectKey: function () {
      const path = this.$route.path;
      const dfs = (data) => {
        for (let i = 0; i < data.length; i++) {
          const item = data[i];
          if (item.children && item.children.length) {
            const a = dfs(item.children);
            if (a) {
              this.openKeys = [item.path];
              break;
            }
          } else if (item.path && path.indexOf(item.path) > -1) {
            return true;
          }
        }
      };
      dfs(menuData);
      return [path];
    },
  },
  mounted() {
    const path = this.$route.path;
    this.menuClick({ key: path });
  },
  methods: {
    subMenuClick(openKeys) {
      this.openKeys = openKeys.splice(-1, 1);
    },
    menuClick({ key }) {
      let menuStack = this.menuStack;
      let isHere = false;
      for (let i = 0; i < this.menuStack.length; i++) {
        if (menuStack[i].path === key) {
          isHere = true;
        }
      }
      if (!isHere) {
        const dfs = (data) => {
          for (let i = 0; i < data.length; i++) {
            const item = data[i];
            if (item.children && item.children.length) {
              const a = dfs(item.children);
              if (a) {
                break;
              }
            } else if (item.path && item.path === key) {
              console.log(item, key);
              menuStack.unshift(item);
              this.$store.commit("common/setMenuStack", menuStack);
              return true;
            }
          }
        };
        dfs(menuData);
      }
    },
  },
  render(h) {
    const selectMenu = [...this.currentSelectKey, ...this.openKeys];
    return (
      <div class="menu">
        <a-menu
          mode="inline"
          openKeys={this.openKeys}
          defaultSelectedKeys={this.currentSelectKey}
          onopenChange={this.subMenuClick}
          onclick={this.menuClick}
          selectedKeys={this.currentSelectKey}
        >
          {menuData.map((item) => {
            return createMenu.call(this, h, item, selectMenu);
          })}
        </a-menu>
      </div>
    );
  },
};