haykou
haykou

Reputation: 387

VueJS: how can i use two computed properties inside one v-for?

I have this computed property:

 computed: {
            filteredCars: function() {
                var self = this
                return self.carros.filter(function(carro) {
                    return carro.nome.indexOf(self.busca) !== -1
                })
            },
        },

and i'm using v-for like this:

<tr v-for="carro in filteredCars">
    <td>{{carro.nome}}</td>
    <td>{{carro.marca}}</td>
    <td>{{carro.categoria}}</td>
    <td>{{carro.motor}}</td>
    <td>{{carro.cambio}}</td>
    <td>{{carro.preco}}</td>
 </tr>

but I need to create another computed property to limit my data quantity, how i call it inside the same v-for?

I'm trying to use filteredCars + another filter, in this case something like 'limit' filter from vue 1.x. I've done an example using Vue 1.x but i need to do using Vue 2.x.

Vue.filter('limit', function (value, amount) {
            return value.filter(function(val, index, arr){
                return index < amount;      
            });

<tr v-for="carro in carros | limit upperLimit>
...
</tr>

Upvotes: 1

Views: 1442

Answers (1)

kevguy
kevguy

Reputation: 4438

Just use Array.prototype.slice (Array.prototype.splice should work too) in the computed property.

data: {
    carros: [...],
    upperLimit: 30
},
computed: {
    filteredCars: function() {
        const arr = this.carros.filter(function(carro) {
            return carro.nome.indexOf(self.busca) !== -1
        });
        if (arr.length > this.upperLimit) {
            return arr.slice(0, this.upperLimit + 1);
        }
        return arr;
    },
}

Upvotes: 2

Related Questions