用vue实现条件检索
用 Vue 实现条件检索
数据绑定与输入框
在 Vue 中实现条件检索通常需要结合 v-model 实现输入框与数据的双向绑定。例如,创建一个搜索输入框:
<template>
<input v-model="searchQuery" placeholder="输入检索条件" />
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
};
}
};
</script>
计算属性过滤数据
使用计算属性 (computed) 动态过滤数据,避免直接修改原始数据。根据 searchQuery 过滤 items:
<script>
export default {
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
}
};
</script>
渲染过滤结果
在模板中渲染过滤后的数据,例如通过 v-for 显示列表:

<template>
<input v-model="searchQuery" placeholder="输入检索条件" />
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
多条件检索扩展
若需支持多条件(如按名称和分类检索),可扩展计算属性逻辑:
<script>
export default {
data() {
return {
searchName: '',
searchCategory: '',
items: [
{ id: 1, name: '苹果', category: '水果' },
{ id: 2, name: '胡萝卜', category: '蔬菜' }
]
};
},
computed: {
filteredItems() {
return this.items.filter(item => {
const nameMatch = item.name.toLowerCase().includes(this.searchName.toLowerCase());
const categoryMatch = item.category.toLowerCase().includes(this.searchCategory.toLowerCase());
return nameMatch && categoryMatch;
});
}
}
};
</script>
异步数据检索
若数据需从 API 获取,可使用 watch 或 methods 配合异步请求:

<script>
export default {
data() {
return {
searchQuery: '',
items: [],
isLoading: false
};
},
watch: {
searchQuery(newVal) {
this.fetchItems(newVal);
}
},
methods: {
async fetchItems(query) {
this.isLoading = true;
try {
const response = await axios.get('/api/items', { params: { q: query } });
this.items = response.data;
} catch (error) {
console.error(error);
} finally {
this.isLoading = false;
}
}
}
};
</script>
使用第三方库优化
对于复杂检索,可集成第三方库如 Lodash 的 _.debounce 减少频繁请求:
import { debounce } from 'lodash';
export default {
methods: {
fetchItems: debounce(function(query) {
// 异步逻辑
}, 500)
}
};
完整示例代码
以下是一个完整的 Vue 条件检索组件示例:
<template>
<div>
<input v-model="searchQuery" placeholder="输入检索条件" />
<ul v-if="!isLoading">
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }} - {{ item.category }}
</li>
</ul>
<p v-else>加载中...</p>
</div>
</template>
<script>
import { debounce } from 'lodash';
export default {
data() {
return {
searchQuery: '',
items: [],
isLoading: false
};
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
},
created() {
this.fetchItems();
},
methods: {
fetchItems: debounce(async function() {
this.isLoading = true;
try {
const response = await fetch('/api/items');
this.items = await response.json();
} catch (error) {
console.error(error);
} finally {
this.isLoading = false;
}
}, 500)
}
};
</script>






