vue实现全局菜单搜索
实现全局菜单搜索功能
在Vue中实现全局菜单搜索功能需要结合路由配置和搜索逻辑。以下是具体实现方法:
创建搜索组件
新建一个Search.vue组件作为全局搜索入口:
<template>
<div class="search-container">
<input
v-model="searchQuery"
placeholder="搜索菜单..."
@input="handleSearch"
/>
<ul v-if="filteredRoutes.length > 0">
<li v-for="route in filteredRoutes" :key="route.path">
<router-link :to="route.path">{{ route.meta.title }}</router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
filteredRoutes: []
}
},
methods: {
handleSearch() {
const query = this.searchQuery.toLowerCase()
this.filteredRoutes = this.$router.options.routes.filter(route => {
return route.meta?.title?.toLowerCase().includes(query)
})
}
}
}
</script>
注册为全局组件
在main.js中全局注册搜索组件:
import Search from '@/components/Search.vue'
const app = createApp(App)
app.component('GlobalSearch', Search)
添加路由元信息
在路由配置中添加meta信息以便搜索:

const routes = [
{
path: '/dashboard',
component: Dashboard,
meta: { title: '控制面板' }
},
{
path: '/users',
component: Users,
meta: { title: '用户管理' }
}
]
实现快捷键触发
添加键盘事件监听触发搜索:
mounted() {
window.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'k') {
this.$refs.searchInput.focus()
}
})
}
样式优化
为搜索组件添加基本样式:

.search-container {
position: relative;
}
.search-container input {
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
}
.search-container ul {
position: absolute;
width: 100%;
background: white;
border: 1px solid #eee;
max-height: 300px;
overflow-y: auto;
}
嵌套路由处理
对于嵌套路由,需要递归处理:
function flattenRoutes(routes) {
return routes.reduce((acc, route) => {
if (route.children) {
acc = acc.concat(flattenRoutes(route.children))
}
return acc.concat(route)
}, [])
}
性能优化
添加防抖减少频繁搜索:
import { debounce } from 'lodash'
methods: {
handleSearch: debounce(function() {
// 搜索逻辑
}, 300)
}
多语言支持
考虑国际化场景:
handleSearch() {
const currentLocale = this.$i18n.locale
this.filteredRoutes = this.$router.options.routes.filter(route => {
const title = route.meta?.title?.[currentLocale] || route.meta?.title
return title?.toLowerCase().includes(this.searchQuery.toLowerCase())
})
}
以上实现方案提供了完整的全局菜单搜索功能,可根据实际项目需求进行调整和扩展。






