[Vuejs]-How to sort multiple objects with watched value? vue

0👍

While you can make it work with a watch, this seems like a better fit for computed

The sort function takes a compare function as an argument, you can dynamically compare the objects based on sort preference by passing it as a key using bracket notation for accessor.

<template>
    <div>
        <select v-model="sortBy">
            <option value="date_installed">Latest</option>
            <option value="status">Status</option>
            <option value="share">Share</option>
        </select>
        <ul>
            <li v-for="item in filtered" :key="item.id">{{ item.app_name}}</li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            sortBy: [],
            affiliates: [
                //...
            ]
        }
    },
    computed: {
        filtered() {
            if (val.length === 0) return this.affiliates;
            return this.affiliates.sort( (a,b) => {
                return a[this.sortBy] - b[this.sortBy]
            });
        }
    },
}
</script>

Leave a comment