如果我在vue.js中有类似下面代码的代码,点击一个按钮后,我怎么才能显示我点击的数组项(例如,Donnie)并隐藏所有其余的? (Joanne,Peter e.t.c),然后当你再次点击唯一显示的元素时,再次显示所有其他数组元素?
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>
答案 0 :(得分:1)
如果已单击某个项目,您应该能够在过滤器表达式中添加身份检查。
首先添加一个属性来存储点击的朋友。我将其称为选择
data {
selected: null,
keyword: '',
//etc
}
然后在您的exclude
方法
exclude (friend) {
this.selected = this.selected ? null : friend
}
现在您的计算属性可以先根据selected
朋友过滤列表,然后再回到关键字匹配
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)
})
}
答案 1 :(得分:1)
我认为这就是你要找的东西:
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"
},
],
selected: null
},
computed: {
filteredList() {
if (!this.selected) {
return this.friends.filter((friend) => {
return friend.name.toLowerCase().includes(this.keyword) + friend.age.includes(this.keyword) + friend.name.includes(this.keyword);
});
} else {
return [this.selected];
}
},
},
methods:{
exclude(friend) {
if(!this.selected) {
this.selected = friend;
} else {
this.selected = null;
}
},
}
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<div v-for="friend in filteredList" class="card" @click="exclude(friend)">
{{friend.name}} - {{friend.age}}
</div>
</div>
这里的诀窍是selected
数据属性存储朋友,如果有朋友,也可以兼作检查者,如果没有,则显示全部,如果是,则只显示该朋友。