vue实现搜索页面
Vue实现搜索页面的方法
基本结构搭建
使用Vue CLI或Vite创建项目,安装必要依赖。搜索页面通常包含输入框、搜索按钮和结果列表组件。
<template>
<div class="search-page">
<input v-model="searchQuery" @keyup.enter="handleSearch" placeholder="输入关键词..."/>
<button @click="handleSearch">搜索</button>
<ul v-if="results.length">
<li v-for="(item, index) in results" :key="index">{{ item.title }}</li>
</ul>
<p v-else>暂无结果</p>
</div>
</template>
数据绑定与事件处理
通过v-model实现双向数据绑定,监听键盘事件或点击事件触发搜索。
<script>
export default {
data() {
return {
searchQuery: '',
results: []
}
},
methods: {
async handleSearch() {
if (!this.searchQuery.trim()) return
try {
const response = await fetch(`/api/search?q=${encodeURIComponent(this.searchQuery)}`)
this.results = await response.json()
} catch (error) {
console.error('搜索失败:', error)
}
}
}
}
</script>
API请求封装
建议将API请求单独封装,便于维护和复用。创建api.js文件:
export const searchAPI = (query) => {
return fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then(response => response.json())
}
结果展示优化
使用计算属性处理搜索结果,添加加载状态和错误提示。
computed: {
hasResults() {
return this.results.length > 0
}
},
data() {
return {
isLoading: false,
error: null
}
},
methods: {
async handleSearch() {
this.isLoading = true
this.error = null
try {
this.results = await searchAPI(this.searchQuery)
} catch (err) {
this.error = '搜索失败,请重试'
} finally {
this.isLoading = false
}
}
}
样式设计
添加基础样式提升用户体验,建议使用CSS预处理器。
<style scoped>
.search-page {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
input {
width: 70%;
padding: 8px;
}
button {
padding: 8px 16px;
margin-left: 10px;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 8px;
border-bottom: 1px solid #eee;
}
</style>
高级功能扩展
实现防抖优化,避免频繁请求API。
import { debounce } from 'lodash'
export default {
created() {
this.debouncedSearch = debounce(this.handleSearch, 500)
},
methods: {
onInputChange() {
this.debouncedSearch()
}
}
}
路由集成
如果使用Vue Router,可以设置搜索页为独立路由。
const routes = [
{
path: '/search',
component: SearchPage,
props: route => ({ query: route.query.q })
}
]
状态管理
对于复杂应用,建议使用Vuex或Pinia管理搜索状态。

// Pinia示例
export const useSearchStore = defineStore('search', {
state: () => ({
results: [],
history: []
}),
actions: {
async search(query) {
const res = await searchAPI(query)
this.results = res
this.history.push(query)
}
}
})






