[Vuejs]-Vue filter function to return always 5 more elements

2👍

The filter function should be used to filter based on the internal values of an array. Say you have an array of objects with persons, and each Person as an age, then you could use the Array.prototype.filter function to filter based on that age of each entry.
The filter function therefore goes through every entry in your array and determines whether an item should be included or excluded.

If you, on the other hand, want to limit the amount of entries based on a maximum number of entries, I would suggest you use Array.prototype.slice, as you mentioned already.

Your computed function could be rewritten to:

activeItems: function() {
    return this.items.slice(0, this.limit)
}

1👍

First, in your code, this.limit is undefined because this is referencing the anonymous function. If you want to access the component, you will better use arrow functions syntax.
Also, s references an element of your array, so s.length will be undefined too I guess…

Now, filter does not seem to be the best choice for your need. I’ll go with slice instead. Somthing like:

computed: {
  activeItems() {
    return this.items.splice(0, this.limit)
  }
}

Where limit is increased by 5 when you click the show more button.

👤J4kim

1👍

Of course you could do it. You just missed some code on it. Here how you fix it

activeItems: function() {
    let limit = this.limit
    return this.items.filter( function(item, s) {
        return s <= limit
    });
}

If you don’t mind using filter, here are some way to do it.

First : put condition in your for loop, this one

<span class="box-content" v-for="(item, index) in items" :key="item.id" v-if="index <= limit">
      <img class="item" :src="item.filename" />
</span>

Second is to slice your array on you desired length, this one

<span class="box-content" v-for="(item, index) in items.slice(0, limit)" :key="item.id">
      <img class="item" :src="item.filename" />
</span>

Leave a comment