update 优化 重新实现菜单搜索功能

This commit is contained in:
疯狂的狮子Li
2026-03-24 17:28:01 +08:00
parent 6ed02a2ddd
commit 4fb60440f2
+419 -108
View File
@@ -1,130 +1,264 @@
<template> <template>
<div class="layout-search-dialog"> <div class="layout-search-dialog">
<el-dialog v-model="state.isShowSearch" destroy-on-close :show-close="false"> <el-dialog
<template #footer> v-model="state.isShowSearch"
<el-autocomplete width="640px"
ref="layoutMenuAutocompleteRef" destroy-on-close
v-model="state.menuQuery" append-to-body
:fetch-suggestions="menuSearch" :show-close="false"
placeholder="搜索" @close="handleClose"
:fit-input-width="true" @opened="onDialogOpened"
@select="onHandleSelect" >
> <el-input
<template #prefix> ref="searchInputRef"
<svg-icon class-name="search-icon" icon-class="search" /> v-model="state.menuQuery"
</template> size="large"
<template #default="{ item }"> clearable
<div> placeholder="菜单搜索,支持标题、URL模糊查询"
<svg-icon :icon-class="item.icon" class="mr5" /> @input="querySearch"
{{ item.title }} @keydown.up.prevent="navigateResult('up')"
@keydown.down.prevent="navigateResult('down')"
@keydown.enter.prevent="selectActiveResult"
>
<template #prefix>
<svg-icon class-name="search-icon" icon-class="search" />
</template>
</el-input>
<div v-if="state.menuQuery && state.options.length > 0" class="result-count">
找到 <strong>{{ state.options.length }}</strong> 个结果
</div>
<el-scrollbar wrap-class="layout-search-scrollbar">
<div class="result-wrap">
<template v-if="state.options.length > 0">
<div
v-for="(item, index) in state.options"
:key="item.path + item.fullTitle"
class="search-item"
:class="{ 'is-active': index === state.activeIndex }"
:style="activeStyle(index)"
@mouseenter="state.activeIndex = index"
@mouseleave="state.activeIndex = -1"
@click="handleSelect(item)"
>
<div class="search-item__icon">
<svg-icon v-if="item.icon" :icon-class="item.icon" class-name="menu-icon" />
<svg-icon v-else icon-class="guide" class-name="menu-icon" />
</div>
<div class="search-item__info">
<div class="menu-title" v-html="highlightText(item.fullTitle)"></div>
<div class="menu-path" v-html="highlightText(item.path)"></div>
</div>
<svg-icon v-show="index === state.activeIndex" icon-class="enter" class-name="search-enter" />
</div> </div>
</template> </template>
</el-autocomplete>
</template> <div v-else-if="state.menuQuery" class="empty-state">
<el-icon class="empty-icon"><Search /></el-icon>
<p class="empty-text">
未找到 "<strong>{{ state.menuQuery }}</strong>" 相关菜单
</p>
<p class="empty-tip">试试其他关键词或路径</p>
</div>
</div>
</el-scrollbar>
<div class="search-footer">
<span class="shortcut-item"><kbd></kbd><kbd></kbd> 切换</span>
<span class="shortcut-item"><kbd></kbd> 选择</span>
<span class="shortcut-item"><kbd>Esc</kbd> 关闭</span>
</div>
</el-dialog> </el-dialog>
</div> </div>
</template> </template>
<script setup lang="ts" name="layoutBreadcrumbSearch"> <script setup lang="ts" name="layoutBreadcrumbSearch">
import { Search } from '@element-plus/icons-vue';
import { getNormalPath } from '@/utils/ruoyi'; import { getNormalPath } from '@/utils/ruoyi';
import { isHttp } from '@/utils/validate'; import { isHttp } from '@/utils/validate';
import { usePermissionStore } from '@/store/modules/permission'; import { usePermissionStore } from '@/store/modules/permission';
import { RouteRecordRaw } from 'vue-router'; import { useSettingsStore } from '@/store/modules/settings';
type Router = Array<{ import type { RouteRecordRaw } from 'vue-router';
type SearchMenuItem = {
path: string; path: string;
icon: string; icon: string;
title: string[]; title: string[];
}>; fullTitle: string;
type SearchState<T = any> = { query?: string;
};
type SearchState = {
isShowSearch: boolean; isShowSearch: boolean;
menuQuery: string; menuQuery: string;
menuList: T[]; menuList: SearchMenuItem[];
options: SearchMenuItem[];
activeIndex: number;
}; };
// 定义变量内容
const layoutMenuAutocompleteRef = ref();
const router = useRouter(); const router = useRouter();
const routes = computed(() => usePermissionStore().routes); const permissionStore = usePermissionStore();
const settingsStore = useSettingsStore();
const searchInputRef = ref<any>();
const routes = computed(() => permissionStore.defaultRoutes);
const theme = computed(() => settingsStore.theme);
const state = reactive<SearchState>({ const state = reactive<SearchState>({
isShowSearch: false, isShowSearch: false,
menuQuery: '', menuQuery: '',
menuList: [] menuList: [],
options: [],
activeIndex: -1
}); });
// 搜索弹窗打开 const buildSearchPool = () => {
state.menuList = generateRoutes(routes.value as RouteRecordRaw[]);
if (!state.menuQuery) {
state.options = state.menuList;
}
};
const openSearch = () => { const openSearch = () => {
state.menuQuery = ''; state.menuQuery = '';
state.activeIndex = -1;
buildSearchPool();
state.isShowSearch = true; state.isShowSearch = true;
state.menuList = generateRoutes(routes.value as any); };
const onDialogOpened = () => {
nextTick(() => { nextTick(() => {
setTimeout(() => { searchInputRef.value?.focus?.();
layoutMenuAutocompleteRef.value.focus();
});
}); });
}; };
// 搜索弹窗关闭
const closeSearch = () => { const handleClose = () => {
searchInputRef.value?.blur?.();
state.menuQuery = '';
state.activeIndex = -1;
state.options = state.menuList;
state.isShowSearch = false; state.isShowSearch = false;
}; };
// 菜单搜索数据过滤
const menuSearch = (queryString: string, cb: (options: any[]) => void) => { const generateRoutes = (routeList: RouteRecordRaw[], basePath = '', prefixTitle: string[] = []): SearchMenuItem[] => {
const options = state.menuList.filter((item) => { let result: SearchMenuItem[] = [];
return item.title.indexOf(queryString) > -1; routeList.forEach((route) => {
if (route.hidden) {
return;
}
const currentPath = route.path?.startsWith('/') ? route.path : `/${route.path ?? ''}`;
const data: SearchMenuItem = {
path: !isHttp(route.path || '') ? getNormalPath(basePath + currentPath) : String(route.path || ''),
icon: String(route.meta?.icon || ''),
title: [...prefixTitle],
fullTitle: ''
};
if (route.meta?.title) {
data.title = [...data.title, String(route.meta.title)];
data.fullTitle = data.title.join(' / ');
if (route.redirect !== 'noRedirect') {
result.push(data);
}
}
if (route.query) {
data.query = String(route.query);
}
if (route.children?.length) {
result = [...result, ...generateRoutes(route.children, data.path, data.title)];
}
}); });
cb(options); return result;
}; };
// Filter out the routes that can be displayed in the sidebar const querySearch = (query: string) => {
// And generate the internationalized title state.activeIndex = -1;
const generateRoutes = (routes: RouteRecordRaw[], basePath = '', prefixTitle: string[] = []) => { if (!query) {
let res: Router = []; state.options = state.menuList;
routes.forEach((r) => { return;
// skip hidden router
if (!r.hidden) {
const p = r.path.length > 0 && r.path[0] === '/' ? r.path : '/' + r.path;
const data: any = {
path: !isHttp(r.path) ? getNormalPath(basePath + p) : r.path,
icon: r.meta?.icon,
title: [...prefixTitle]
};
if (r.meta && r.meta.title) {
data.title = [...data.title, r.meta.title];
if (r.redirect !== 'noRedirect') {
// only push the routes with title
// special case: need to exclude parent router without redirect
res.push(data);
}
}
// recursive child routes
if (r.children) {
const tempRoutes = generateRoutes(r.children, data.path, data.title);
if (tempRoutes.length >= 1) {
res = [...res, ...tempRoutes];
}
}
}
});
res.forEach((item: any) => {
if (item.title instanceof Array) {
item.title = item.title.join('/');
}
});
return res;
};
// 当前菜单选中时
const onHandleSelect = (val: any) => {
const paths = val.path;
if (isHttp(paths)) {
// http(s):// 路径新窗口打开
const pindex = paths.indexOf('http');
window.open(paths.substring(pindex, paths.length), '_blank');
} else {
router.push(paths);
} }
state.menuQuery = '';
closeSearch(); const keyword = query.toLowerCase();
state.options = state.menuList.filter((item) => {
return item.fullTitle.toLowerCase().includes(keyword) || item.path.toLowerCase().includes(keyword);
});
}; };
// 暴露变量 const navigateResult = (direction: 'up' | 'down') => {
if (!state.options.length) {
return;
}
if (direction === 'up') {
state.activeIndex = state.activeIndex <= 0 ? state.options.length - 1 : state.activeIndex - 1;
return;
}
state.activeIndex = state.activeIndex >= state.options.length - 1 ? 0 : state.activeIndex + 1;
};
const selectActiveResult = () => {
if (state.options.length === 0) {
return;
}
const current = state.activeIndex >= 0 ? state.options[state.activeIndex] : state.options[0];
handleSelect(current);
};
const handleSelect = async (item: SearchMenuItem) => {
if (isHttp(item.path)) {
const startIndex = item.path.indexOf('http');
window.open(item.path.substring(startIndex), '_blank');
} else if (item.query) {
try {
await router.push({ path: item.path, query: JSON.parse(item.query) });
} catch {
await router.push(item.path);
}
} else {
await router.push(item.path);
}
handleClose();
};
const activeStyle = (index: number) => {
if (index !== state.activeIndex) {
return {};
}
return {
backgroundColor: theme.value,
color: '#fff'
};
};
const highlightText = (text: string) => {
if (!text || !state.menuQuery) {
return text;
}
const escapedKeyword = escapeRegExp(state.menuQuery);
const reg = new RegExp(`(${escapedKeyword})`, 'gi');
return text.replace(reg, '<span class="highlight">$1</span>');
};
const escapeRegExp = (value: string) => {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};
watch(
routes,
() => {
buildSearchPool();
},
{ deep: true, immediate: true }
);
defineExpose({ defineExpose({
openSearch openSearch
}); });
@@ -132,30 +266,207 @@ defineExpose({
<style lang="scss" scoped> <style lang="scss" scoped>
.layout-search-dialog { .layout-search-dialog {
position: relative;
:deep(.el-dialog) { :deep(.el-dialog) {
border-radius: 22px;
overflow: hidden;
padding: 0; padding: 0;
.el-dialog__header, }
.el-dialog__body {
display: none; :deep(.el-dialog__header) {
display: none;
}
:deep(.el-dialog__body) {
padding: 18px 18px 0;
}
:deep(.el-input__wrapper) {
min-height: 52px;
border-radius: 16px;
}
:deep(.highlight) {
color: #ef4444;
font-weight: 600;
}
:deep(.is-active .highlight) {
color: rgba(255, 255, 255, 0.92);
}
}
.result-count {
padding: 10px 6px 0;
font-size: 12px;
color: var(--app-text-muted);
strong {
color: #ef4444;
font-weight: 600;
}
}
.result-wrap {
height: 300px;
margin: 8px 0 0;
}
.search-item {
display: flex;
align-items: center;
gap: 12px;
min-height: 56px;
margin-bottom: 6px;
padding: 10px 12px;
border-radius: 16px;
cursor: pointer;
transition:
background-color 0.18s ease,
transform 0.18s ease,
color 0.18s ease;
&:hover {
transform: translateY(-1px);
background: rgba(64, 158, 255, 0.08);
}
&.is-active {
transform: none;
}
}
.search-item__icon {
width: 28px;
display: inline-flex;
justify-content: center;
flex-shrink: 0;
.menu-icon {
width: 18px;
height: 18px;
}
}
.search-item__info {
flex: 1;
min-width: 0;
}
.menu-title,
.menu-path {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.menu-title {
font-size: 14px;
font-weight: 600;
color: inherit;
}
.menu-path {
margin-top: 4px;
font-size: 12px;
color: var(--app-text-muted);
}
.search-item.is-active .menu-path {
color: rgba(255, 255, 255, 0.8);
}
.search-enter {
width: 16px;
height: 16px;
flex-shrink: 0;
}
.empty-state {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: var(--app-text-muted);
}
.empty-icon {
font-size: 40px;
margin-bottom: 14px;
color: #cbd5e1;
}
.empty-text {
margin: 0 0 6px;
font-size: 14px;
strong {
color: var(--app-text-title);
}
}
.empty-tip {
margin: 0;
font-size: 12px;
}
.search-footer {
display: flex;
align-items: center;
gap: 24px;
padding: 14px 18px 16px;
border-top: 1px solid rgba(148, 163, 184, 0.12);
color: var(--app-text-muted);
font-size: 12px;
}
.shortcut-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
kbd {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 20px;
height: 20px;
padding: 0 5px;
border: 1px solid rgba(148, 163, 184, 0.28);
border-radius: 6px;
background: rgba(248, 250, 252, 0.9);
color: var(--app-text-title);
font-size: 11px;
line-height: 1;
box-shadow: inset 0 -1px 0 rgba(148, 163, 184, 0.18);
}
:global(html.dark) {
.layout-search-dialog {
:deep(.el-dialog) {
background: linear-gradient(180deg, rgba(15, 23, 42, 0.98), rgba(30, 41, 59, 0.95));
} }
.el-dialog__footer {
width: 100%; :deep(.el-input__wrapper) {
position: absolute; background: rgba(15, 23, 42, 0.92);
left: 50%; box-shadow: inset 0 0 0 1px rgba(71, 85, 105, 0.38);
transform: translateX(-50%);
top: -53vh;
padding: 0;
border-top: none;
background: transparent;
} }
} }
:deep(.el-autocomplete) {
width: 560px; .search-item:hover {
position: absolute; background: rgba(59, 130, 246, 0.16);
top: 150px; }
left: 50%;
transform: translateX(-50%); .empty-icon {
color: #64748b;
}
kbd {
background: rgba(30, 41, 59, 0.9);
border-color: rgba(71, 85, 105, 0.48);
color: #e2e8f0;
box-shadow: inset 0 -1px 0 rgba(15, 23, 42, 0.5);
} }
} }
</style> </style>