Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Building Vue.js Applications with GraphQL

You're reading from   Building Vue.js Applications with GraphQL Develop a complete full-stack chat app from scratch using Vue.js, Quasar Framework, and AWS Amplify

Arrow left icon
Product type Book
Published in Jan 2021
Publisher Packt
ISBN-13 9781800565074
Pages 298 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
Heitor Ramon Ribeiro Heitor Ramon Ribeiro
Author Profile Icon Heitor Ramon Ribeiro
Heitor Ramon Ribeiro
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

Preface 1. Data Binding, Events, and Computed Properties 2. Components, Mixins, and Functional Components FREE CHAPTER 3. Setting Up Our Chat App - AWS Amplify Environment and GraphQL 4. Creating Custom Application Components and Layouts 5. Creating the User Vuex Module, Pages, and Routes 6. Creating Chat and Message Vuex, Pages, and Routes 7. Transforming Your App into a PWA and Deploying to the Web 8. Other Books You May Enjoy

Creating conditional filters to sort list data

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:

  1. 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>
  1. 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>
  1. 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
Remember to always execute the command npm run lint --fix, to automatically fix any code lint error.

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:

  1. 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.
  2. 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.
  3. 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

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime