I want to filter the fetched json data by clicking buttons so that only data (in my case book name) which are matched with the button clicked should be shown and hide the other data (books) which are not matched until another button matching the other name is clicked.
I have populated the data as list on my component as follows:
<li v-for"(book, i) in books" :key="i">
{{book.name}}
</li>
and they are rendered correctly as follows:
- The Alchemist
- Harry Potter
- etc...
Now, I have buttons (hard coded) which I need them to filter the results and show the only those buttons are clicked.
<button>The Alchemist</button>
<button>Harry Potter</button>
and here is my json data:
[{
"name": "The Alchemist",
"author": "Paulo Coelho",
"year": "1988",
},
{
"name": "Harry Potter",
"author": "J. K. Rowling",
"year": "1997",
}]
any idea to solve it will be appreciated
CodePudding user response:
Working Demo :
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);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button v-for="(book, i) in books" :key="i" @click="filterData($event)">{{ book.name }}</button>
<li v-for="(book, i) in filteredBooks" :key="i">
{{ book.name }}
</li>
</div>