如果我的 vue.js 中有类似下面代码的代码,那么在单击按钮时,如何才能只显示我单击的数组项(例如 Donnie)并隐藏所有其余项? (Joanne、Peter 等),那么当您再次单击唯一显示的元素时,是否使所有其他数组元素再次显示?
const app = new Vue({
el: '#app',
data: {
keyword: '',
friends: [
{
name: "Donnie",
age: "20"
},
{
name: "Joanne",
age:"19",
},
{
name: "David",
age: "26"
},
{
name: "Peter",
age: "23"
},
{
name: "John",
age: "29"
},
{
name: "Jason",
age: "19"
},
],
},
computed: {
filteredList() {
return this.friends.filter((friend) => {
return friend.name.toLowerCase().includes(this.keyword) + friend.age.includes(this.keyword) + friend.name.includes(this.keyword);
});
}
},
methods:{
exclude(friend) {
console.log(!friend.name);
},
}
})
HTML
<div v-for="friend in filteredList" class="card" @click="exclude(friend)">
{{friend.name}} - {{friend.age}}
</div>
最佳答案
如果单击了某个项目,您应该能够向过滤器表达式添加身份检查。
首先添加一个属性来存储点击的好友。我将调用我的选定
data {
selected: null,
keyword: '',
//etc
}
然后在您的排除
方法中
exclude (friend) {
this.selected = this.selected ? null : friend
}
现在您的计算属性可以首先根据所选
friend 过滤列表,然后再回退到关键字匹配
filteredList () {
return this.selected ? [this.selected] : this.friends.filter(friend => {
let search = this.keyword.trim().toLowerCase()
return friend.name.toLowerCase().includes(search) || friend.age.includes(search)
})
}
关于javascript - Vue.js - 只显示错误的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50614568/