vue 搜索框实现跳转
实现 Vue 搜索框跳转功能
在 Vue 中实现搜索框跳转功能通常涉及监听用户输入、处理搜索逻辑以及路由跳转。以下是两种常见实现方式:

基础实现方式(基于 Vue Router)
<template>
<div>
<input
v-model="searchQuery"
@keyup.enter="handleSearch"
placeholder="输入关键词搜索"
>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: ''
}
},
methods: {
handleSearch() {
if (this.searchQuery.trim()) {
this.$router.push({
path: '/search',
query: { q: this.searchQuery }
})
}
}
}
}
</script>
带自动补全的搜索实现
<template>
<div class="search-container">
<input
v-model="searchQuery"
@input="handleInput"
@keyup.enter="performSearch"
placeholder="搜索..."
>
<ul v-if="suggestions.length" class="suggestions">
<li
v-for="(item, index) in suggestions"
:key="index"
@click="selectSuggestion(item)"
>
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
suggestions: [],
timeout: null
}
},
methods: {
handleInput() {
clearTimeout(this.timeout)
if (this.searchQuery.length > 2) {
this.timeout = setTimeout(this.fetchSuggestions, 300)
} else {
this.suggestions = []
}
},
fetchSuggestions() {
// 这里替换为实际的API调用
this.suggestions = ['建议1', '建议2', '建议3']
},
selectSuggestion(item) {
this.searchQuery = item
this.suggestions = []
this.performSearch()
},
performSearch() {
if (this.searchQuery.trim()) {
this.$router.push({
path: '/search-results',
query: { query: this.searchQuery }
})
}
}
}
}
</script>
<style scoped>
.search-container {
position: relative;
}
.suggestions {
position: absolute;
width: 100%;
background: white;
list-style: none;
padding: 0;
margin: 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.suggestions li {
padding: 8px 12px;
cursor: pointer;
}
.suggestions li:hover {
background: #f5f5f5;
}
</style>
使用 Vuex 管理搜索状态
对于大型应用,建议使用 Vuex 集中管理搜索状态:

// store/modules/search.js
export default {
state: {
searchQuery: '',
searchResults: []
},
mutations: {
SET_SEARCH_QUERY(state, query) {
state.searchQuery = query
},
SET_SEARCH_RESULTS(state, results) {
state.searchResults = results
}
},
actions: {
async performSearch({ commit, state }) {
const results = await searchApi(state.searchQuery)
commit('SET_SEARCH_RESULTS', results)
}
}
}
路由配置示例
在 router.js 中配置搜索结果页面:
const routes = [
{
path: '/search',
name: 'SearchResults',
component: SearchResults,
props: route => ({ query: route.query.q })
}
]
搜索结果页面组件
<template>
<div>
<h2>搜索结果: {{ query }}</h2>
<!-- 显示搜索结果 -->
</div>
</template>
<script>
export default {
props: ['query'],
watch: {
query(newVal) {
this.fetchResults(newVal)
}
},
created() {
this.fetchResults(this.query)
},
methods: {
fetchResults(query) {
// 调用API获取结果
}
}
}
</script>
以上实现方式可根据具体需求进行组合和调整,满足不同场景下的搜索跳转需求。






