vue实现搜索联想
Vue 实现搜索联想功能
搜索联想(Search Suggest)功能可以在用户输入时实时提供相关的搜索建议,提升用户体验。以下是实现搜索联想功能的几种方法:
使用 Vue 的 v-model 和 watch
通过 Vue 的 v-model 绑定输入框的值,并使用 watch 监听输入变化,触发联想逻辑。
<template>
<div>
<input v-model="searchQuery" placeholder="输入搜索内容" />
<ul v-if="suggestions.length">
<li v-for="(suggestion, index) in suggestions" :key="index">
{{ suggestion }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
suggestions: []
};
},
watch: {
searchQuery(newVal) {
if (newVal.length > 0) {
this.fetchSuggestions(newVal);
} else {
this.suggestions = [];
}
}
},
methods: {
async fetchSuggestions(query) {
try {
const response = await axios.get('/api/suggestions', {
params: { q: query }
});
this.suggestions = response.data;
} catch (error) {
console.error('获取联想建议失败:', error);
}
}
}
};
</script>
使用防抖优化性能
频繁触发搜索联想请求会导致性能问题,可以使用防抖(debounce)技术优化。
<script>
import { debounce } from 'lodash';
export default {
data() {
return {
searchQuery: '',
suggestions: []
};
},
created() {
this.debouncedFetchSuggestions = debounce(this.fetchSuggestions, 300);
},
watch: {
searchQuery(newVal) {
if (newVal.length > 0) {
this.debouncedFetchSuggestions(newVal);
} else {
this.suggestions = [];
}
}
},
methods: {
async fetchSuggestions(query) {
try {
const response = await axios.get('/api/suggestions', {
params: { q: query }
});
this.suggestions = response.data;
} catch (error) {
console.error('获取联想建议失败:', error);
}
}
}
};
</script>
使用自定义指令实现
可以通过自定义指令封装搜索联想功能,便于复用。
<template>
<div>
<input v-search-suggest v-model="searchQuery" placeholder="输入搜索内容" />
<ul v-if="suggestions.length">
<li v-for="(suggestion, index) in suggestions" :key="index">
{{ suggestion }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
suggestions: []
};
},
directives: {
'search-suggest': {
inserted(el, binding, vnode) {
el.addEventListener('input', async (e) => {
const query = e.target.value;
if (query.length > 0) {
try {
const response = await axios.get('/api/suggestions', {
params: { q: query }
});
vnode.context.suggestions = response.data;
} catch (error) {
console.error('获取联想建议失败:', error);
}
} else {
vnode.context.suggestions = [];
}
});
}
}
}
};
</script>
使用第三方库
可以使用现成的 Vue 搜索联想库,如 vue-suggest 或 vue-autosuggest,快速实现功能。
安装 vue-autosuggest:
npm install vue-autosuggest
示例代码:
<template>
<div>
<vue-autosuggest
v-model="searchQuery"
:suggestions="suggestions"
@input="onInputChange"
/>
</div>
</template>
<script>
import VueAutosuggest from 'vue-autosuggest';
export default {
components: {
VueAutosuggest
},
data() {
return {
searchQuery: '',
suggestions: []
};
},
methods: {
async onInputChange(query) {
if (query.length > 0) {
try {
const response = await axios.get('/api/suggestions', {
params: { q: query }
});
this.suggestions = response.data;
} catch (error) {
console.error('获取联想建议失败:', error);
}
} else {
this.suggestions = [];
}
}
}
};
</script>
本地数据过滤
如果联想数据量较小,可以直接在前端进行过滤,减少网络请求。
<script>
export default {
data() {
return {
searchQuery: '',
allSuggestions: ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'],
suggestions: []
};
},
watch: {
searchQuery(newVal) {
if (newVal.length > 0) {
this.suggestions = this.allSuggestions.filter(item =>
item.toLowerCase().includes(newVal.toLowerCase())
);
} else {
this.suggestions = [];
}
}
}
};
</script>
以上方法可以根据实际需求选择适合的实现方式。







