Now that you've completed the previous recipe, your data should be filtered and sorted, but you might need to check the filtered data or need to change how it was sorted. In this recipe, you will learn how to create conditional filters and sort the data on a list.
Using some basic principles, it's possible to gather information and display it in many different ways.
Getting ready
The prerequisite for this recipe is Node.js 12+.
The Node.js global objects that are required for this recipe are as follows:
- @vue/cli
- @vue/cli-service-global
We can continue with our to-do list project or create a new Vue project with the Vue CLI, as we learned in the Creating your first project with the Vue CLI recipe.
How to do it...
Follow these steps to add a conditional filter to sort your list data:
- In the App.vue file, at the <script> part, we will update the computed properties; that is, filteredList, sortedList, and displayList. We need to add three new variables to our project: hideDone, reverse, and sortById. All three are going to be Boolean variables and will start with a default value of false. The filteredList property will check if the hideDone variable is true. If it is, it will have the same behavior, but if not, it will show the whole list with no filter. The sortedList property will check if the sortById variable is true. If it is, it will have the same behavior, but if not, it will sort the list by the finished date of the task. Finally, the displayList property will check if the reverse variable is true. If it is, it will reverse the displayed list, but if not, it will have the same behavior:
<script>
import CurrentTime from "./components/CurrentTime.vue";
import TaskInput from "./components/TaskInput";
export default {
name: "TodoApp",
components: {
CurrentTime,
TaskInput
},
data: () => ({
taskList: [],
hideDone: false,
reverse: false,
sortById: false,
}),
computed: {
baseList() {
return [...this.taskList]
.map((t, index) => ({
...t,
id: index + 1
}));
},
filteredList() {
return this.hideDone
? [...this.baseList]
.filter(t => !t.finishedAt)
: [...this.baseList];
},
sortedList() {
return [...this.filteredList]
.sort((a, b) => (
this.sortById
? b.id - a.id
: (a.finishedAt || 0) - (b.finishedAt || 0)
));
},
displayList() {
const taskList = [...this.sortedList];
return this.reverse
? taskList.reverse()
: taskList;
}
},
methods: {
formatDate(value) {
if (!value) return "";
if (typeof value !== "number") return value;
const browserLocale =
navigator.languages && navigator.languages.length
? navigator.languages[0]
: navigator.language;
const intlDateTime = new Intl.DateTimeFormat(browserLocale, {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric"
});
return intlDateTime.format(new Date(value));
},
addNewTask(task) {
this.taskList.push({
task,
createdAt: Date.now(),
finishedAt: undefined
});
},
changeStatus(taskId) {
const task = this.taskList[taskId - 1];
if (task.finishedAt) {
task.finishedAt = undefined;
} else {
task.finishedAt = Date.now();
}
}
}
};
</script>
- For the <template> part, we need to add the controllers for those variables. We will create three checkboxes, linked directly to the variables via the v-model directive:
<template>
<div id="app">
<current-time class="col-4" />
<task-input class="col-6" @add-task="addNewTask" />
<div class="col-12">
<div class="cardBox">
<div class="container">
<h2>My Tasks</h2>
<hr />
<div class="col-4">
<input
v-model="hideDone"
type="checkbox"
id="hideDone"
name="hideDone"
/>
<label for="hideDone">
Hide Done Tasks
</label>
</div>
<div class="col-4">
<input
v-model="reverse"
type="checkbox"
id="reverse"
name="reverse"
/>
<label for="reverse">
Reverse Order
</label>
</div>
<div class="col-4">
<input
v-model="sortById"
type="checkbox"
id="sortById"
name="sortById"
/>
<label for="sortById">
Sort By Id
</label>
</div>
<ul class="taskList">
<li
v-for="(taskItem, index) in displayList"
:key="`${index}_${Math.random()}`"
>
<input type="checkbox"
:checked="!!taskItem.finishedAt"
@input="changeStatus(taskItem.id)"
/>
#{{ taskItem.id }} - {{ taskItem.task }}
<span v-if="taskItem.finishedAt"> |
Done at:
{{ formatDate(taskItem.finishedAt) }}
</span>
</li>
</ul>
</div>
</div>
</div>
</div>
</template>
- To run the server and see your component, you need to open a Terminal (macOS or Linux) or Command Prompt/PowerShell (Windows) and execute the following command:
> npm run serve
Here is the component rendered and running:
How it works...
The computed properties worked together as a cache for the list and made sure there weren't any side effects when it came to manipulating the elements. With the conditional process, it was possible to change the rules for the filtering and sorting processes through a variable, and the display was updated in real time:
- For the filteredList property, we took the baseList property and returned just the tasks that weren't finished. When the hideDone variable was false, we returned the whole list without any filter.
- For the sortedList property, we sorted the tasks on the filteredList property. When the sortById variable was true, the list was sorted by ID in descending order; when it was false, the sorting was done by the task's finish time in ascending order.
- For the displayList property, when the reverse variable was true, the final list was reversed.
When all the manipulation was done, the displayList property returned the result of the data that was manipulated.
These computed properties were controlled by the checkboxes on the user screen, so the user had total control of what they could see and how they could see it.
See also
- You can find more information about Array.prototype.map at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map.
- You can find more information about Array.prototype.filter at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter.
- You can find more information about Array.prototype.sort at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.