vue计算属性是实现搜索过滤最简洁高效的方式,它自动响应数据变化、缓存结果且无需手动触发;核心是监听searchterm,用filter()匹配name或category字段并统一转小写提升容错性。

Vue 的计算属性(computed)是实现搜索过滤最简洁高效的方式——它自动响应数据变化、缓存结果、无需手动触发,特别适合实时更新的列表筛选。
用 computed 实现基础关键词搜索
核心思路:监听搜索输入框的值(如 searchTerm),在计算属性中对原始列表做 filter() 处理,返回匹配项。
示例代码:
data() {
return {
searchTerm: '',
list: [
{ id: 1, name: '苹果', category: '水果' },
{ id: 2, name: '香蕉', category: '水果' },
{ id: 3, name: '胡萝卜', category: '蔬菜' }
]
}
},
computed: {
filteredList() {
if (!this.searchTerm.trim()) return this.list;
const keyword = this.searchTerm.toLowerCase();
return this.list.filter(item =>
item.name.toLowerCase().includes(keyword) ||
item.category.toLowerCase().includes(keyword)
);
}
}
注意点:
- 先判断空字符串或空白字符,避免无意义过滤
- 统一转小写(toLowerCase())提升匹配容错性
- 可同时匹配多个字段(如 name、category),用 || 连接
支持多条件组合筛选(如分类 + 搜索)
当页面有下拉筛选(如“水果”“蔬菜”)和搜索框共存时,把多个筛选条件都纳入同一个计算属性中,保持响应式联动。
扩展 data:
分析 Vue 3 Composition API 使用情况——审计响应式模式、可组合函数设计、ref 与 reactive 的选择、计算属性、watcher 使用及组件……
data() {
return {
searchTerm: '',
selectedCategory: '', // '' 表示全部
list: [/* 同上 */]
}
},
computed: {
filteredList() {
return this.list.filter(item => {
const matchesSearch = !this.searchTerm.trim() ||
item.name.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
item.category.toLowerCase().includes(this.searchTerm.toLowerCase());
<pre class="brush:php;toolbar:false;"> const matchesCategory = !this.selectedCategory ||
item.category === this.selectedCategory;
return matchesSearch && matchesCategory;
});} }
这样用户切换分类或输入文字,列表自动实时更新,无需额外 watch 或方法。
优化性能:防抖不是 computed 的事,但要懂边界
计算属性本身不防抖——它每次依赖变化都会重新求值。如果搜索框绑定的是原生 input 事件(非 debounce 后的),快速打字会高频触发 filter。
实际建议:
- 普通列表(
- 大数据量或复杂匹配逻辑:把输入框改用 debounced search,即用 watch + setTimeout 控制更新频率,再把防抖后的值作为 computed 的依赖
- 不要在 computed 内写 setTimeout 或异步操作——计算属性必须同步返回值
进阶:支持模糊匹配与高亮(可选增强)
计算属性只负责“筛选”,但常需配套“高亮”。可拆分为两个计算属性:
- filteredList:专注过滤逻辑
-
getHighlightedText:接收原始文本和关键词,返回带
<span class="highlight"></span>的 HTML 字符串(配合 v-html 使用)
例如:
computed: {
getHighlightedText() {
return (text) => {
if (!this.searchTerm.trim()) return text;
const escaped = this.searchTerm.replace(/[.*+?^${}()|[]\]/g, '\$&');
const regex = new RegExp(`(${escaped})`, 'gi');
return text.replace(regex, '<span class="highlight">$1</span>');
};
}
}
模板中使用:v-html="getHighlightedText(item.name)",记得加 CSS 类 .highlight 设置背景色。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!









