Proper way of sorting list in v-for Hi guys !
Could you please help me with solution to my problem. In my simple vue app I have a component: Todo-item witch is used in v-for loop like this:
<div class="todo-list">
<todo-item v-for= item in items></todo-item>
</div>
My todos in data
...
data: {
items: {
{name: "task 1" value: "30"},
{name: "task 2" value: "60"},
{name: "task 3" value: "5"},
{name: "task 4" value: "10"}
}
}
...
I want to add a
<select>
<option>Sort by Name</option>
<option>Sort by Value</option>
</select>
What is the proper way of dealing with this kind o problem ? I want to be able to sort my items by value selected from select input. Cheers
@topvillas Could share some example ? Right now I created something like this I have used computed to create list for v-for
computed: {
listItems() {
return _.orderBy(this.items, 'value', 'desc');
}
and in my html
<div class="todo-list">
<todo-item v-for="item in listItems"></todo-item>
</div>
But what If I want to order it by name also in one select AND how to connect select values to computed value ? how to solve this ?
You can bind the select input to a variable which you can then use to filter through the items using a method.
<template>
<div class="wrapper">
<select v-model="currentOrder">
<option value="name">Sort by Name</option>
<option value="value">Sort by Value</option>
</select>
<div class="todo-list">
<todo-item v-for="item in orderedItems(items)" :key="item.name"></todo-item>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentOrder: 'value',
items: [
{name: "task 1" value: "30"},
{name: "task 2" value: "60"},
{name: "task 3" value: "5"},
{name: "task 4" value: "10"}
]
}
},
methods: {
toggleOrder(name) {
this.currentOrder = name;
},
orderedItems(items) {
return items.filter(item => {
if (item[this.currentOrder]) return item;
});
}
}
}
</script>
Please sign in or create an account to participate in this conversation.