vue实现搜索自动查询
Vue实现搜索自动查询
实现搜索自动查询功能通常涉及监听输入框的变化,并在用户输入时触发搜索请求。以下是几种常见的实现方式:
使用v-model和watch监听输入变化
通过v-model绑定输入框的值,并使用watch监听变化,配合防抖函数避免频繁请求。
<template>
<input v-model="searchQuery" placeholder="搜索...">
</template>
<script>
export default {
data() {
return {
searchQuery: '',
debounceTimer: null
}
},
watch: {
searchQuery(newVal) {
clearTimeout(this.debounceTimer)
this.debounceTimer = setTimeout(() => {
this.performSearch(newVal)
}, 500) // 500ms防抖延迟
}
},
methods: {
performSearch(query) {
// 执行搜索API调用
console.log('正在搜索:', query)
}
}
}
</script>
使用计算属性和watch的组合
对于需要更复杂逻辑的情况,可以结合计算属性使用。
<template>
<input v-model="searchQuery" placeholder="搜索...">
</template>
<script>
export default {
data() {
return {
searchQuery: '',
searchResults: []
}
},
computed: {
normalizedQuery() {
return this.searchQuery.trim().toLowerCase()
}
},
watch: {
normalizedQuery: {
handler(newVal) {
if (newVal.length > 2) { // 至少3个字符才搜索
this.performSearch(newVal)
}
},
immediate: false
}
},
methods: {
async performSearch(query) {
try {
const response = await axios.get(`/api/search?q=${query}`)
this.searchResults = response.data
} catch (error) {
console.error('搜索失败:', error)
}
}
}
}
</script>
使用自定义指令实现防抖
可以创建自定义指令来封装防抖逻辑,使模板更简洁。
// 注册全局防抖指令
Vue.directive('debounce', {
inserted(el, binding) {
let timer
el.addEventListener('input', () => {
clearTimeout(timer)
timer = setTimeout(() => {
binding.value()
}, 500)
})
}
})
// 组件中使用
<template>
<input v-model="searchQuery" v-debounce="search" placeholder="搜索...">
</template>
<script>
export default {
data() {
return {
searchQuery: ''
}
},
methods: {
search() {
console.log('执行搜索:', this.searchQuery)
}
}
}
</script>
使用第三方库如lodash的防抖函数
对于更复杂的防抖需求,可以使用lodash的防抖函数。
import { debounce } from 'lodash'
export default {
data() {
return {
searchQuery: ''
}
},
created() {
this.debouncedSearch = debounce(this.performSearch, 500)
},
watch: {
searchQuery(newVal) {
this.debouncedSearch(newVal)
}
},
methods: {
performSearch(query) {
console.log('执行搜索:', query)
}
}
}
显示搜索建议
实现搜索建议功能可以在用户输入时显示匹配的结果列表。
<template>
<div>
<input v-model="searchQuery" @input="showSuggestions" placeholder="搜索...">
<ul v-if="suggestions.length">
<li v-for="(item, index) in suggestions" :key="index" @click="selectSuggestion(item)">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
suggestions: [],
allItems: ['苹果', '香蕉', '橙子', '西瓜', '葡萄'] // 示例数据
}
},
methods: {
showSuggestions() {
if (this.searchQuery.length > 0) {
this.suggestions = this.allItems.filter(item =>
item.includes(this.searchQuery)
)
} else {
this.suggestions = []
}
},
selectSuggestion(item) {
this.searchQuery = item
this.suggestions = []
this.performSearch(item)
}
}
}
</script>
以上方法可以根据具体需求选择或组合使用,核心思想是通过监听输入变化并配合防抖机制来优化性能。







