【发布时间】:2019-01-20 21:41:41
【问题描述】:
我正在构建一个键命令资源,并在此过程中让 VueJS 试一试。我是一个新手,但正在掌握事物(慢慢地......)。
我希望能够在全局搜索表单中搜索我在命令部分中定义为 动作 的关键命令(请参阅下面的数据示例)。我想搜索所有操作以仅显示与搜索条件匹配的操作。
我的 HTML 如下:
<div id="commands">
<input v-model="searchQuery" />
<div class="commands-section" v-for="item in sectionsSearched"
:key="item.id">
<h3>{{ item.section }}</h3>
<div class="commands-row" v-for="command in item.command" :key="command.action">
{{ command.action }}
</div>
</div>
</div>
我的主 Vue 实例如下所示:
import Vue from 'vue/dist/vue.esm'
import { commands } from './data.js'
document.addEventListener('DOMContentLoaded', () => {
const element = document.getElementById("commands")
if (element != null) {
const app = new Vue({
el: element,
data: {
searchQuery: '',
commands: commands
},
computed: {
sectionsSearched() {
var self = this;
return this.commands.filter((c) => {
return c.command.filter((item) => {
console.log(item.action)
return item.action.indexOf(self.searchQuery) > -1;
});
});
},
}
});
}
});
最后是data.js中的数据结构
const commands = [
{
section: "first section",
command: [
{ action: '1' },
{ action: '2' },
{ action: '3' },
],
},
{
section: "second section",
command: [
{ action: 'A' },
{ action: 'B' },
{ action: 'C' },
]
},
]
export { commands };
我可以使用console.log(item.action) sn-p 输出命令,您在称为sectionsSearched 的计算方法中看到。
我在浏览器中看不到任何错误,并且数据正确呈现。
我不能但是通过实时搜索进行过滤。我几乎肯定它是我的数据结构+计算方法的组合。任何人都可以了解我在这里做错了什么吗?
理想情况下,我希望保持数据不变,因为分割很重要。
我是一名 Rails 人,对这些东西不熟悉,因此欢迎提供任何和所有反馈。
谢谢!
编辑
我已经尝试了以下建议的解决方案,但在我通过的任何查询中都会收到undefined。在大多数情况下,该功能似乎适用于以下情况:
sectionsSearched() {
return this.commands.filter((c) => {
return c.command.filter((item) => {
return item.action.indexOf(this.searchQuery) > -1;
}).length > 0;
});
},
但遗憾的是,实际上什么都没有回来。我正在努力挠头。
【问题讨论】:
标签: javascript search vue.js vuejs2