Summer Sale! All accounts are 50% off this week.

ekrist1's avatar

Sort v-for list with calculated field

I have a v-for loop which runs a method to calculate a price for each vendor. Is there any ways to sort the list according to low-high prices using computed properties?

<div class="mt-4 mb-4 mr-3 border-2 border-grey p-4 bg-grey-lightest sm:w-full md:w-2/5" v-for="vendor in vendors" :key="vendor.id">
<h3{{ vendor.company }}</h3>
 <p class="text-darker">Agreementname: {{ vendor.agreement_type }}</p>
<p class="text-darker">Vendor price: {{ vendor.price }} kr</p>
<p class="text-darker">Fee: {{ vendor.fee }}</p>
<powercontact :vendordescription="vendor.description"></powercontact>
>div class="flex items-center bg-orange text-white text-sm font-bold px-4 py-3 mt-6" role="alert">
<p> Price per month {{ calculatePrice(vendor.fee, vendor.price, vendor.invoice) | roundCalculatedPrice }},-</p>
</div>
</div>
0 likes
5 replies
bobbybouwmann's avatar
Level 88

You should use a computed property for this. For example

// SortableTable.vue

<template>
    <div v-for="vendor in sortedVendors">
        <h3{{ vendor.company }}</h3>
    </div>
</template>

<script>

export default {

    data() {
        return {
            vendors: [],    
    },

    computed: {
            sortedVendors: function () {
            return this.vendors.filter(function (vendor) {
                return calculatePrice(vendor);
            });
        },
    },

    methods: {
        calculatePrice(vendor) {
            return vendor.price;
        }
    },
}

</script>

Documentation: https://vuejs.org/v2/guide/computed.html#Computed-Properties

Note that you can also sort your data on the server side. In above example vuejs is responsible for sorting it, but you can also let your query sort it.

1 like
ekrist1's avatar

@bobbybouwmann thanks :) this will solve my issue. I'm using Laravel as backend, but with your solution I don't need to post any data back to the server.

Please or to participate in this conversation.