For reference I'm using laravel 8 with blade syntax.
This line of code is part of a vue component I made:
<li
v-if="comic.item_type === 'b' && comic.stock > 0"
v-for="(comic, index) in [...list].slice(0, 20)">
in the
.slice(0, 20)
I want to make the 20 dynamic. I'm using the V-for lop to render items on a page, but I want to limit the rendered items to 20 instances, until a 'load more' button is clicked, so the plan is to create a function that increases this parameter by 20 each time it is clicked.
I'm new to Vue, so if there is a better way to do this, please let me know!
I have tried making the second parameter a bound class, but it just (obviously) throws an error, as it's not supposed to be used that way.
CodePudding user response:
Try like following snippet:
const app = Vue.createApp({
data() {
return {
list: [{"id": 1, "name": "aaa", "item_type": "b", "stock": 9, }, {"id": 2, "name": "bbb", "item_type": "b", "stock": 11, }, {"id": 3, "name": "ccc", "item_type": "b", "stock": 8, }, {"id": 4, "name": "ddd", "item_type": "b", "stock": 8, }, {"id": 5, "name": "eee", "item_type": "b", "stock": 8, }, {"id": 6, "name": "fff", "item_type": "a", "stock": 8, }, {"id": 7, "name": "ggg", "item_type": "b", "stock": 8, }],
nr: 2
}
},
computed: {
filteredComics() {
return [...this.list.filter(l => l.item_type === 'b' && l.stock > 0)]
},
comics() {
return this.filteredComics.slice(0, this.nr)
}
},
methods: {
loadMore() {
this.nr = this.nr this.nr
}
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<ul>
<li v-for="(comic, index) in comics">
{{ comic.name }}
</li>
</ul>
<button @click="loadMore" v-if="nr < filteredComics.length">more</button>
</div>
CodePudding user response:
I would go for a computed list variable (containing the pre-filtered actual list) along with an loadMoreTimes
index (how much the "load more"-button was pressed) that provides a simple access to the filtered list like so:
computed: {
filteredList() {
return this.list
.filter(comic => comic.item_type === 'b' && comic.stock > 0)
.slice(0, (this.loadMoreTimes 1) * 20);
}
}
You can then simply loop over that array
<li
v-for="(comic, index) in filteredList">
BTW: it is not a good practice to use v-if
and v-for
in the same element.