Vue.js 搜索功能实现:使用 Prompt 属性传递搜索关键字
<h2>Vue.js 搜索功能实现:使用 Prompt 属性传递搜索关键字</h2>
<p>本文将介绍如何在 Vue.js 组件中实现搜索功能,并使用 <code>prompt</code> 属性将搜索关键字传递给组件,以便进行数据过滤和展示。html<template> <div> <input type='text' v-model='searchKeyword' @keyup.enter='onSearch'> <ul> <li v-for='item in filteredItems' :key='item.id'> {{ item.name }} </li> </ul> </div></template></p>
<script>export default { data() { return { is_list: true, is_data: false, searchTag: [ { id: 1, name: '西红柿虫害识别' }, { id: 2, name: '数据加载中' } ], searchKeyword: '', // 搜索关键字 prompt: '', response: '', loading: false }; }, methods: { // 搜索触发 onSearch() { // 将搜索关键字赋值给 prompt this.prompt = this.searchKeyword;
// 执行搜索逻辑,例如过滤数据 this.submitData(); }, submitData() { // 在此处实现具体的搜索逻辑,例如发送请求到后端接口 // ... } }, computed: { // 根据搜索关键字过滤数据 filteredItems() { if (this.searchKeyword === '') { return this.searchTag; } else { return this.searchTag.filter(item => { return item.name.toLowerCase().includes(this.searchKeyword.toLowerCase()); }); } } }};</script>
<p><strong>代码解释:</strong></p>
<ol>
<li><strong>搜索框:</strong> 使用 <code>v-model</code> 指令将搜索框的值绑定到 <code>searchKeyword</code> 数据属性。2. <strong>搜索触发:</strong> 使用 <code>@keyup.enter</code> 监听回车键事件,触发 <code>onSearch</code> 方法。3. <strong>onSearch 方法:</strong> 将 <code>searchKeyword</code> 的值赋给 <code>prompt</code> 属性,并将 <code>prompt</code> 传递给 <code>submitData</code> 方法进行搜索。4. <strong>submitData 方法:</strong> 在该方法中实现具体的搜索逻辑,例如发送请求到后端接口获取搜索结果。5. <strong>数据展示:</strong> 使用 <code>v-for</code> 指令循环遍历 <code>filteredItems</code> 计算属性,展示过滤后的数据。</li>
</ol>
<p><strong>总结:</strong></p>
<p>通过上述代码,我们实现了在 Vue.js 组件中使用 <code>prompt</code> 属性传递搜索关键字的功能,并根据搜索关键字动态过滤数据。你可以根据实际需求修改 <code>submitData</code> 方法中的搜索逻辑,以实现更复杂的搜索功能。</p>
原文地址: https://www.cveoy.top/t/topic/fYCq 著作权归作者所有。请勿转载和采集!