Filtering data is one of the most common features of any data-facing application, whether it’s a front-end application or a back-end application. The Filter function is used to find records in a table or a dataset that meets certain criteria. For example, if you have a list called Books in a webpage, and you want to only show books that are currently on sale. You could accomplish this using the filter function.
In this short tutorial we are building a single page web app with two parts. The first part will be a list of students. The list will be displayed in a table like structure with multiple columns for each student. Each column will correspond to a data attribute of the student record. The list will also have a summary line at the end that tells you the record count. This is the student data structure:
student: {
id: unique identifier,
firstName: string,
lastName: string,
dob: date (date of birth),
gpa: number,
address: string,
city: string,
county: string,
state: string,
zip: number
}
The second part will be the filters that the user can use to filter the data with. Let’s assume that the user can filter by any field displayed in the list. So to build generic filter functions, that can be used with multiple fields, we will need to group these filters by data type. And each data type will allow certain comparison operators. The following table illustrate this logic.
string: [contains, startWith]
date: [equal, greaterThan, lessThan, between]
number: [equal, greaterThan, lessThan, between]
lookup: [is, isNot]
So basically we can build 12 comparison function that we can use with all our fields or any fields that we may add in the future. So let’s get started with our app and see how we can build these features.
To start a new app, you will need to install Vue and open new terminal window and type the following:
# initiating new Vue app
vue create col-admin
Vue CLI v3.0.0-rc.9
┌───────────────────────────┐
│ Update available: 3.5.1 │
└───────────────────────────┘
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, Linter
? Pick a linter / formatter config: Standard
? Pick additional lint features: Lint on save
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? No
# adding other js libraries
vue add vue-cli-plugin-vuetify
? Choose a preset: Default (recommended)
✔ Successfully invoked generator for plugin: vue-cli-plugin-vuetify
# adding the backend library
npm install --save cosmicjs
after this we should have our starter application ready to be customized. If you want to run the app, just open the terminal window and type npm run serve and then open the application from your browser from this app default url http://localhost:8080/ and you're good to go to the next step.
As we mentioned earlier, the goal of this app is to display a list of students, and then use the filter functionality to narrow down the list. For this project we will use Cosmic JS to store our data, and also to server the data using the built-in Rest API that comes with Cosmic JS.
From the object type metafields tab, add the following fields:
SID: text field, firstName: text field, lastName: text field, DOB: text field, GPA: text field, Address: text field, City: text field, County: text field, State: text field, Zip: text field
Add some data into the Students table. If you want you can copy my data table from Cosmic JS by importing my col-admin-bucket under your account. I have inserted about 300 records, so you don’t have to type all these information manually.
Access your Cosmic JS data via the built-in Rest API from this url: https://api.cosmicjs.com/v1/col-admin/objects?type=students
Take a look to the Cosmic JS API Documentations for a detailed list of all the APIs available for you.
After this you should be able to access you backend data via the Rest API.
Under our project root folder lets add new folder `./src/store/` and move `./src/store.js` under the store folder. We will also need to create new file under `./src/api/cosmic.js`
<a href="https://medium.com/media/78e322b8574bf434052f67691614c68e/href">https://medium.com/media/78e322b8574bf434052f67691614c68e/href</a>
This small script will be used as Cosmic JS connection object.
We will also need to create new file under ./src/store/modules/cosmic.js for all the Cosmic JS data related functions.
<a href="https://medium.com/media/a6029bb787a40f18ae791b7e4675258a/href">https://medium.com/media/a6029bb787a40f18ae791b7e4675258a/href</a>
So far, we only have one function fetchStudents. This function will call the Cosmic JS getObjects to pull 25 records at a time. And it will do this inside a while loop until we reach the end or no more records can be found. We can identify the end of data of the data row count will be less than 25 records. After fetching all data from the Rest API we will call the ADD_STUDENTSmutation to store these records inside Vuex state variable. For more info about Vuex store, please read the documentation.
There is another call at the end of this function to fetchStates. This function will simply loop through all students records and get the unique state code and store it in states variable. This can be used later on the filter by state dropdown component.
This is the rest of the Vuex store.
<a href="https://medium.com/media/03583d1c6ae321f6cb69f23e0310ce4d/href">https://medium.com/media/03583d1c6ae321f6cb69f23e0310ce4d/href</a>
For this project we will use Vuetify as our fron-end components library. This is very helpful, especially if you like to use Google Material Design into your project without a lot of overhead. Plus Vuetify is awesome because it has tons of built-in UI components that are fully loaded. After adding Vuetify to your project using Vue CLI add command, you can just reference Vuetify components from your page templates. Let’s take a look at the App.vue main layout.
<a href="https://medium.com/media/221deadca1fda3d26f94fb6aca57d10a/href">https://medium.com/media/221deadca1fda3d26f94fb6aca57d10a/href</a>
In the template above you can see that our application page layout has three sections:
You may notice that under the ‘./src’ folder, there are two folders:
In the Home.vue page we will have two main sections:
So let’s take a look at the home page template:
<a href="https://medium.com/media/5f13233a2c744b217b0b5f7a560d85c8/href">https://medium.com/media/5f13233a2c744b217b0b5f7a560d85c8/href</a>
As you can see, from the code above. the v-data-table component is using filteredStudentsvariable as it's data source. Inside Vuex store we have two state variables:
The data-table component also has three sections:
As seen in the Home.vue page template the filters components consist of the following components:
We can summarize the filter functionality by these variables:
headers: [
{ text: 'ID', align: 'left', sortable: false, value: 'id' },
{ text: 'First', value: 'firstName' },
{ text: 'Last', value: 'lastName' },
{ text: 'DOB', value: 'dob', dataType: 'Date' },
{ text: 'GPA', value: 'gpa' },
{ text: 'Address', value: 'address' },
{ text: 'City', value: 'city' },
{ text: 'County', value: 'county' },
{ text: 'State', value: 'state' },
{ text: 'Zip', value: 'zip' }
],
This the data table headers.
filterFields: [
{text: 'First Name', value: 'firstName', type: 'text'},
{text: 'Last Name', value: 'lastName', type: 'text'},
{text: 'DOB', value: 'dob', type: 'date'},
{text: 'GPA', value: 'gpa', type: 'number'},
{text: 'Address', value: 'address', type: 'text'},
{text: 'City', value: 'city', type: 'text'},
{text: 'County', value: 'county', type: 'text'},
{text: 'Zip', value: 'zip', type: 'number'},
{text: 'State', value: 'state', type: 'lookup'}
],
This is the list of filter fields that the user can select. You can also see that I added a type for each filter field. Filter type will be used lated to decide which function will be called to run the filter operations. Many fields will have the same data types, therefore we don’t need to call a separate function to filter by that field. We will call the same function for all fields that share the same data type.
<a href="https://medium.com/media/5dbd157c386b427cbf5c5f0637ba618f/href">https://medium.com/media/5dbd157c386b427cbf5c5f0637ba618f/href</a>
The filterDefs variable will store information that tells our UI which operator to use on each field type. We also specify in this config variable, which Javascript function to call when we need to filter by the selected field. This variable is my own interpretation on how the filter function should be configured and designed, however you can certainly do without it, and use Javascript code with a lot of if statements.
The last piece is the actual Javascript functions that we will call for each filter type. I am not going to list all of them, but let’s see few examples from the Home.vue page
<a href="https://medium.com/media/16c152901b0b59d9c429b84e94c30b76/href">https://medium.com/media/16c152901b0b59d9c429b84e94c30b76/href</a>
The code above have two functions filterByTextContains and filterByTextStartsWithwhich will be called each time the user uses the text field filter function. And behind those two functions we call filterByRegExp which is basically a function that uses Javascript Regular expression function.In a similar way I have written filter functions for numeric fields, for date fields, and for lookup fields. I have used simple logic like date comparison, or array find, or plain old JS if statement. The most important part is that these function should be generic enough to work with any field, and expects few parameters like the data list that should be filtered, the field name and the field value.I encourage you to take a look at the code for Home.vue for the full details.
You can also find inside ‘./src/views/Home.vue’ a couple methods under computed, watch, and filters. Here is how and why I use each type for.
I also want to mention that I have used Vue life cycle event hooks to initiate the data fetching from the back end whenever the application starts. I am doing that from the ./main.js file
<a href="https://medium.com/media/d0b2e7387a2b1cf3f713f9393da950e0/href">https://medium.com/media/d0b2e7387a2b1cf3f713f9393da950e0/href</a>
As you can see, on app created event we are calling Vuex action by invoking the dispatch methods. this is very useful if you want to trigger actions automatically without waiting for user actions.And this is the final result. Please take a look at the application demo for a test drive.
At the end, I want to mention that building simple application like this sounds easy, however building an expandable app can take some thinking and a little planing to make sure that your code can easily allow future expanssions and changes without the need to rewrite the app.Also worth mentioning that, using an API ready back-end did certainly save us a lot of time. Lastly I want to add that after finishing the app I realize that the the Home.vue page could certainly be broken up into small components, and make it more readable and maintainable. So that would probably be the next step if you ever want to make a use of Vue Components.
So, try the application demo, take a look at the source code and let me know what you think.