首页  >  问答  >  正文

点击按钮时,对返回的JSON数据进行VueJS过滤

我想通过单击按钮来过滤获取的 json 数据,以便仅显示与单击的按钮匹配的数据(在我的案例书名称中),并隐藏直到另一个按钮才匹配的其他数据(书籍)单击匹配的其他名称。

我已将数据填充为组件上的列表,如下所示:

<li v-for"(book, i) in books" :key="i">
   {{book.name}}
</li>

它们正确呈现如下:

  1. 炼金术士
  2. 哈利·波特
  3. 等等...

现在,我有按钮(硬编码),我需要它们来过滤结果并显示仅单击的那些按钮。

<button>The Alchemist</button>
<button>Harry Potter</button>

这是我的 json 数据:

[{
 "name": "The Alchemist",
 "author": "Paulo Coelho",
 "year":  "1988",            
 },
{
 "name": "Harry Potter",
 "author": "J. K. Rowling",
 "year":  "1997",            
 }]

任何解决该问题的想法将不胜感激

P粉125450549P粉125450549205 天前358

全部回复(1)我来回复

  • P粉619896145

    P粉6198961452024-03-28 10:41:42

    工作演示:

    new Vue({
      el: '#app',
      data: {
        books: [{
          "name": "The Alchemist",
          "author": "Paulo Coelho",
          "year":  "1988",            
        }, {
          "name": "Harry Potter",
          "author": "J. K. Rowling",
          "year":  "1997",            
        }],
        filteredBooks: []
      },
      mounted() {
        this.filteredBooks = this.books;
      },
      methods: {
        filterData(e) {
          this.filteredBooks = this.books.filter((obj) => obj.name === e.target.textContent);
        }
      }
    });
    sssccc
    
  • {{ book.name }}
  • 回复
    0
  • 取消回复