search

Home  >  Q&A  >  body text

When the button is clicked, perform VueJS filtering on the returned JSON data

I want to filter the json data I get by clicking a button so that only the data that matches the button clicked (in my case book name) is shown and other data that doesn't match until another button is hidden (books ) click on the other name that matches.

I have populated the data as a list on the component like this:

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

They are correctly rendered as follows:

  1. Alchemist
  2. Harry Potter
  3. etc...

Now, I have buttons (hardcoded) and I need them to filter the results and show only those buttons clicked.

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

This is my json data:

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

Any ideas to solve this problem would be greatly appreciated

P粉125450549P粉125450549272 days ago433

reply all(1)I'll reply

  • P粉619896145

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

    Working Demonstration:

    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 }}
  • reply
    0
  • Cancelreply