【问题标题】:VueJS: how can i use two computed properties inside one v-for?VueJS:如何在一个 v-for 中使用两个计算属性?
【发布时间】:2023-03-08 01:44:01
【问题描述】:

我有这个计算属性:

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

我正在像这样使用 v-for:

<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>

但是我需要创建另一个计算属性来限制我的数据量,我如何在同一个 v-for 中调用它?

我正在尝试使用 filteredCars + 另一个过滤器,在这种情况下,类似于 vue 1.x 中的“限制”过滤器。我已经使用 Vue 1.x 做了一个示例,但我需要使用 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>

【问题讨论】:

  • 创建另一个返回的计算,比如filteredCars.slice(1, 30) 或类似的,然后使用它。
  • 你能解释一下究竟你想做什么吗?
  • @RoyJ 是,但这是正确的做法吗?

标签: filter vue.js vuejs2


【解决方案1】:

只需在计算属性中使用Array.prototype.sliceArray.prototype.splice 也可以使用)。

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;
    },
}

【讨论】:

    猜你喜欢
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2019-06-19
    • 2022-06-23
    • 2022-12-17
    • 2018-03-14
    • 1970-01-01
    相关资源
    最近更新 更多