vben
2020-11-01 f645680a3b9a1f75395329970551d9e5d6bd845b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import type { MenuState } from './types';
import type { Menu as MenuType } from '/@/router/types';
 
import { computed, defineComponent, unref, reactive, toRef, watch, onMounted, ref } from 'vue';
import { basicProps } from './props';
import { Menu } from 'ant-design-vue';
import { MenuModeEnum, MenuTypeEnum } from '/@/enums/menuEnum';
import { menuStore } from '/@/store/modules/menu';
import { getSlot } from '/@/utils/helper/tsxHelper';
// import { ScrollContainer } from '/@/components/Container/index';
import SearchInput from './SearchInput.vue';
import './index.less';
import { menuHasChildren } from './helper';
import MenuContent from './MenuContent';
import { useSearchInput } from './useSearchInput';
import { useOpenKeys } from './useOpenKeys';
import { useRouter } from 'vue-router';
import { isFunction } from '/@/utils/is';
import { getCurrentParentPath } from '/@/router/menus';
export default defineComponent({
  name: 'BasicMenu',
  props: basicProps,
  emits: ['menuClick'],
  setup(props, { slots, emit }) {
    const currentParentPath = ref('');
    const menuState = reactive<MenuState>({
      defaultSelectedKeys: [],
      mode: props.mode,
      theme: computed(() => props.theme),
      openKeys: [],
      searchValue: '',
      selectedKeys: [],
      collapsedOpenKeys: [],
    });
    const { currentRoute } = useRouter();
 
    const { handleInputChange, handleInputClick } = useSearchInput({
      flatMenusRef: toRef(props, 'flatItems'),
      emit: emit,
      menuState,
      handleMenuChange,
    });
 
    const { handleOpenChange, resetKeys, setOpenKeys } = useOpenKeys(
      menuState,
      toRef(props, 'items'),
      toRef(props, 'flatItems'),
      toRef(props, 'isAppMenu'),
      toRef(props, 'mode')
    );
 
    const getOpenKeys = computed(() => {
      if (props.isAppMenu) {
        return menuStore.getCollapsedState ? menuState.collapsedOpenKeys : menuState.openKeys;
      }
      return menuState.openKeys;
    });
 
    // menu外层样式
    const getMenuWrapStyle = computed((): any => {
      const { showLogo, search } = props;
      let offset = 0;
      if (search) {
        offset += 54;
      }
      if (showLogo) {
        offset += 46;
      }
      return {
        height: `calc(100% - ${offset - 10}px)`,
        position: 'relative',
        overflow: 'auto',
      };
    });
 
    // 是否透明化左侧一级菜单
    const transparentMenuClass = computed(() => {
      const { type } = props;
      const { mode } = menuState;
      if (
        [MenuTypeEnum.MIX, MenuTypeEnum.SIDEBAR].includes(type) &&
        mode !== MenuModeEnum.HORIZONTAL
      ) {
        return `basic-menu-bg__sidebar`;
      }
      if (
        (type === MenuTypeEnum.TOP_MENU && mode === MenuModeEnum.HORIZONTAL) ||
        props.appendClass
      ) {
        return `basic-menu-bg__sidebar-hor`;
      }
      return '';
    });
 
    watch(
      () => currentRoute.value.name,
      (name: string) => {
        name !== 'Redirect' && handleMenuChange();
        getParentPath();
      }
    );
 
    watch(
      () => props.items,
      () => {
        if (props.items) {
          handleMenuChange();
        }
      },
      {
        immediate: true,
      }
    );
 
    async function getParentPath() {
      const { appendClass } = props;
      if (!appendClass) return '';
      const parentPath = await getCurrentParentPath(unref(currentRoute).path);
      currentParentPath.value = parentPath;
    }
 
    async function handleMenuClick(menu: MenuType) {
      const { beforeClickFn } = props;
      if (beforeClickFn && isFunction(beforeClickFn)) {
        const flag = await beforeClickFn(menu);
        if (!flag) {
          return;
        }
      }
      const { path } = menu;
      menuState.selectedKeys = [path];
      emit('menuClick', menu);
    }
 
    function handleMenuChange() {
      const { flatItems } = props;
      if (!unref(flatItems) || flatItems.length === 0) {
        return;
      }
      const findMenu = flatItems.find((menu) => menu.path === unref(currentRoute).path);
      if (findMenu) {
        if (menuState.mode !== MenuModeEnum.HORIZONTAL) {
          setOpenKeys(findMenu);
        }
        menuState.selectedKeys = [findMenu.path];
      } else {
        resetKeys();
      }
    }
 
    const showTitle = computed(() => {
      if (props.isTop) return true;
      if (!props.isAppMenu) return true;
      if (!props.collapsedShowTitle) {
        return !menuStore.getCollapsedState;
      }
      return true;
    });
 
    // render menu item
    function renderMenuItem(menuList?: MenuType[], index = 1) {
      if (!menuList) {
        return;
      }
      const { appendClass } = props;
      const levelCls = `basic-menu-item__level${index} ${menuState.theme} `;
 
      return menuList.map((menu) => {
        if (!menu) {
          return null;
        }
 
        const isAppendActiveCls =
          appendClass && index === 1 && menu.path === unref(currentParentPath);
        // 没有子节点
        if (!menuHasChildren(menu)) {
          return (
            <Menu.Item
              key={menu.path}
              class={`${levelCls}${isAppendActiveCls ? ' top-active-menu ' : ''}`}
              onClick={handleMenuClick.bind(null, menu)}
            >
              {() => [
                <MenuContent
                  item={menu}
                  level={index}
                  showTitle={unref(showTitle)}
                  searchValue={menuState.searchValue}
                />,
              ]}
            </Menu.Item>
          );
        }
        return (
          <Menu.SubMenu key={menu.path} class={levelCls}>
            {{
              title: () => [
                <MenuContent
                  showTitle={unref(showTitle)}
                  item={menu}
                  level={index}
                  searchValue={menuState.searchValue}
                />,
              ],
              default: () => renderMenuItem(menu.children, index + 1),
            }}
          </Menu.SubMenu>
        );
      });
    }
 
    function renderMenu() {
      const isInline = props.mode === MenuModeEnum.INLINE;
      const { selectedKeys, defaultSelectedKeys, mode, theme } = menuState;
 
      const inlineCollapsedObj = isInline
        ? props.isAppMenu
          ? {
              inlineCollapsed: menuStore.getCollapsedState,
            }
          : { inlineCollapsed: props.inlineCollapsed }
        : {};
      return (
        <Menu
          forceSubMenuRender={props.isAppMenu}
          selectedKeys={selectedKeys}
          defaultSelectedKeys={defaultSelectedKeys}
          mode={mode}
          openKeys={unref(getOpenKeys)}
          inlineIndent={props.inlineIndent}
          theme={unref(theme)}
          onOpenChange={handleOpenChange}
          class={[
            'basic-menu',
            props.collapsedShowTitle && 'collapsed-show-title',
            unref(transparentMenuClass),
          ]}
          {...inlineCollapsedObj}
        >
          {{
            default: () => renderMenuItem(props.items, 1),
          }}
        </Menu>
      );
    }
 
    onMounted(async () => {
      getParentPath();
    });
    return () => {
      const { getCollapsedState } = menuStore;
      const { mode } = props;
      return mode === MenuModeEnum.HORIZONTAL ? (
        renderMenu()
      ) : (
        <section class={[`basic-menu-wrap`, !unref(showTitle) && 'hide-title']}>
          {getSlot(slots, 'header')}
          <SearchInput
            class={!props.search ? 'hidden' : ''}
            theme={props.theme}
            onChange={handleInputChange}
            onClick={handleInputClick}
            collapsed={getCollapsedState}
          />
          <section style={unref(getMenuWrapStyle)} class="basic-menu__wrap">
            {renderMenu()}
            {/* <ScrollContainer>{() => renderMenu()}</ScrollContainer> */}
          </section>
        </section>
      );
    };
  },
});