Vue.js——如何显示错误的数组元素?

  • 回答 (2)
  • 关注 (0)
  • 查看 (101)

如果我的代码如下面的代码在我的vue.js中,点击一个按钮后,我怎样才能显示我点击的数组项目(例如,Donnie)并隐藏其余的所有内容?那么当你再次点击唯一显示的元素时,再次显示所有其他数组元素?

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>
你孩子啊你孩子啊提问于
叮当叮当スターバーストするには回答于

我想这就是你想要的:

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>
脸滚键盘dj以梦为马,诗酒趁年华回答于

如果项目已被点击,你应该能够为你的过滤器表达式添加身份检查。

首先添加一个属性:

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)
  })
}

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励