我正在创建一个动态搜索栏,它会根据用户输入过滤充满名称的侧栏。但是,我无法根据搜索栏在keyup上的值暂时隐藏和显示数据。实现“Vue方式”的最佳方法是什么?
在keyup上,我想过滤所有this.people数据,只显示包含搜索输入值的名称。
以下是我的代码
//Javascript
Vue.component('sidebar',{
props: ['people', 'tables'],
data: () => {
return {
fullName: ''
}
},
computed: {
computed() {
return [this.people, this.tables].join()
}
},
template:
`
<div id="sidebarContain" v-if="this.people">
<input id="sidebar-search" type="text" placeholder="Search..." @keydown="searchQuery">
<select id="sidebar-select" @change="sidebarChanged">
<option value="AZ">A-Z</option>
<option value="ZA">Z-A</option>
<option value="notAtTable">No Table</option>
<option value="Dean's Guest">Dean's Guest</option>
<option value="BOO | VIP">BOO | VIP</option>
</select>
<div v-for="person in people" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id" :style="calcRegColor(person)">
<span v-if="person.table_name">{{person.first_name + ' ' + person.last_name + ' - ' + person.table_name}}</span>
<span v-else>{{person.first_name + ' ' + person.last_name}}</span>
</div>
</div>
`,
methods: {
isCheckedIn(person) {
return person.reg_scan == null ? true : false;
},
isHidden(person)
{
console.log("here");
},
calcRegColor(person)
{
switch(person.registration_type)
{
case "Dean's Guest" :
return {
color: 'purple'
}
break;
case "BOO | VIP" :
return {
color: 'brown'
}
break;
case "Student" :
return {
color: 'green'
}
break;
case "Faculty":
case "Staff":
return {
color: 'blue'
}
break;
case "Alumni Club Leader":
return {
color: 'gold'
}
break;
case "Table Guest" :
return {
color: 'pink'
}
break;
default:
return {
color: 'black'
}
}
}
},
watch: {
computed() {
console.log("People and Tables Available");
}
}
});
//HTML
<div id="app">
<sidebar :people="people" :tables="tables"></sidebar>
</div>
答案 0 :(得分:1)
这是在Vue中实现这一目标的策略:
一个。使用v-for
代替的其他属性
props.people,如myPeople
。
<div v-for="person in myPeople">
B中。使用v-model保存searchQuery:
<input id="sidebar-search" ... v-model="searchQuery">
...
// Include searchQuery in data so it is reactive.
data: () => {
return {
fullName: '',
searchQuery: ''
}
}
℃。 searchQuery更改时计算myPeople
computed: {
myPeople: function () {
return this.people.filter((p) => {
// something based on `searchQuery`
});
}
}
Vue docs对这类事情进行了较长时间的讨论。