vue表单实现搜索
Vue 表单搜索实现方法
基础表单绑定
使用 v-model 实现双向数据绑定,监听用户输入。示例代码:
<template>
<input v-model="searchQuery" placeholder="输入搜索关键词">
</template>
<script>
export default {
data() {
return {
searchQuery: ''
}
}
}
</script>
实时搜索功能
结合 watch 或 computed 属性实现实时响应:
watch: {
searchQuery(newVal) {
this.debouncedSearch(newVal)
}
},
methods: {
debouncedSearch: _.debounce(function(query) {
this.fetchResults(query)
}, 500)
}
搜索结果展示
使用 v-for 渲染过滤后的结果:
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
服务端搜索集成
通过 axios 发送请求到后端 API:
methods: {
fetchResults(query) {
axios.get('/api/search', { params: { q: query } })
.then(response => {
this.results = response.data
})
}
}
表单验证
添加基础输入验证:
data() {
return {
searchQuery: '',
errors: []
}
},
methods: {
validateSearch() {
this.errors = []
if (this.searchQuery.length < 2) {
this.errors.push('关键词至少需要2个字符')
}
}
}
高级功能实现
-
多条件筛选:
computed: { filteredItems() { return this.items.filter(item => { return ( item.name.includes(this.searchQuery) || item.description.includes(this.searchQuery) ) }) } } -
搜索历史记录:
methods: { saveToHistory(query) { if (!this.searchHistory.includes(query)) { this.searchHistory.unshift(query) } } }







