Vue, the versatile filtering tool for data tables in HTML

I am currently using Vue to populate an HTML table with data retrieved from an axios call. The table layout is perfect, but I am interested in finding a way (without converting the entire structure to datatables) to enable filtering on each column header. This way, users can filter multiple columns simultaneously. For example, if the 'Resources' column contains values like 'Truck', 'Trailer', and 'Container', I envision having a dropdown filter on the header of that column. Users could then select 'Truck' to only display rows that contain 'Truck' in the 'Resources' column.

Does that explanation make sense? Is there a built-in method in Vue that allows this kind of functionality?

<table style="width:100%; text-align:center;">
<thead>
    <tr>
        <th>Title</th>
        <th>Resource</th>
        <th>Location</th>
        <th>Status</th>
    </tr>
</thead>
<tbody  v-for="dateEvent in dateEvents">
    <tr>
        <td v-if="dateEvent.id === '2'">{{ dateEvent.title }}</td>
        <td v-if="dateEvent.id === '2'">{{ dateEvent.resource }}</td>
        <td v-if="dateEvent.id === '2'">{{ dateEvent.location }}</td>
        <td v-if="dateEvent.id === '2'">{{ dateEvent.status }}</td>
    </tr>
  </tbody>
</table>



data () {
return {
    dateEvents: []
},
created() {
    this.fetchItems();
},
methods: {
    fetchItems() {
        axios.get('/home/resource_items')
        .then(response => {
          // handle success
          console.log(response.data)
          this.dateEvents = response.data
        })
        .catch(function(error) {
          console.log(error)
        })
        .finally(function() {})
    }
 }

Answer №1

To automatically calculate the following using the `computed` functionality:

  • A filtered array of `dateEvents` for displaying in a table
  • An array of `titles` for displaying in the filter
  • An array of `resources` for displaying in the filter
  • An array of `locations` for displaying in the filter
  • An array of `statuses` for displaying in the filter

Here is a sample implementation:

...

<select v-model="filters.title">
  <option v-for="title in titles" :value="title">{{ title }}</option>
</select>

<select v-model="filters.resource">
  <option v-for="resource in resources" :value="resource">{{ resource }}</option>
</select>

<select v-model="filters.location">
  <option v-for="location in locations" :value="location">{{ location }}</option>
</select>

<select v-model="filters.status">
  <option v-for="status in statuses" :value="status">{{ status }}</option>
</select>

<button @click="reset">Reset</button>

...

  <tbody v-for="dateEvent in filtered">
    <tr>
      <td>{{ dateEvent.title }}</td>
      <td>{{ dateEvent.resource }}</td>
      <td>{{ dateEvent.location }}</td>
      <td>{{ dateEvent.status }}</td>
    </tr>
  </tbody>

...

data() {
  return {
    dateEvents: [],
    filters: {
      title: null,
      resource: null,
      location: null,
      status: null,
    },
  };
},


computed() {

  filtered() {
    return this.dataEvents
      .filter(dataEvent => !this.filters.title || dataEvent.title === this.filters.title),
      .filter(dataEvent => !this.filters.resource || dataEvent.resource === this.filters.resource),
      .filter(dataEvent => !this.filters.location || dataEvent.location === this.filters.location),
      .filter(dataEvent => !this.filters.status || dataEvent.status === this.filters.status);
  },

  titles() {
    return this.dataEvents
      .map(dataEvent => dataEvent.title)
      .filter((title, index, self) => self.indexOf(title) === index);
  },

  resources() {
    return this.dataEvents
      .map(dataEvent => dataEvent.resource)
      .filter((resource, index, self) => self.indexOf(resource) === index);
  },

  locations() {
    return this.dataEvents
      .map(dataEvent => dataEvent.location)
      .filter((location, index, self) => self.indexOf(location) === index);
  },

  statuses() {
    return this.dataEvents
      .map(dataEvent => dataEvent.status)
      .filter((status, index, self) => self.indexOf(status) === index);
  },
},


methods: {

  reset() {
    this.filters.title = null;
    this.filters.resource = null;
    this.filters.location = null;
    this.filters.status = null;
  },

},

...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to execute multiple Protractor test suites simultaneously?

Exploring Protractor for the first time. My goal is to run multiple test suites in a sequence. I have a complex angular form with various scenarios, each with its expected results. I want to execute all tests with just one command. Initially, I tried enter ...

Using the Google Identity Services JavaScript SDK in conjunction with Vue and TypeScript: A comprehensive guide

I am currently working on authorizing Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript application. Following the guidelines provided here, I have included the Google 3P Authorization JavaScript Library in ...

Use an array to store nested JSON fields

I'm currently seeking to enhance my proficiency in utilizing JavasScript, React, and Material-UI. I am faced with the challenge of sorting my table using a nested JSON structure and I am encountering difficulties with assigning the JSON fields to my a ...

Transform your standard HTML buttons into a collective of radio buttons

Looking for a way to make some ordinary buttons function as radio buttons without adding another library to the project. Any suggestions on how this can be achieved using just HTML and JavaScript/jQuery? Appreciate any help, thank you. ...

Trouble arises with Javascript object destructuring when used with this.props in React

Just recently I discovered object destructuring with a basic object, which worked perfectly. However, when attempting to apply it in React on this.props, all my variables are returning as undefined. I'm unsure of what mistake I might be making here. A ...

Converting a unix timestamp to a Date in TypeScript - a comprehensive guide

To retrieve the unix timestamp of a Date in plain JavaScript and TypeScript, we can use this code snippet: let currentDate = new Date(); const unixTime = currentDate.valueOf(); Converting the unix timestamp back to a Date object in JavaScript is straight ...

Tips for setting the scroll back to the top when switching between pages in quasar

Whenever a qlist item is clicked by the user, it redirects to another page. However, the scrolled position from the previous page is retained and not set to the top. This means that the user has to manually scroll back to the top to view the contents of th ...

What is the process for viewing the collections of all databases while logged in as an administrator?

My aim is to display all databases along with their collections, similar to logging in as an admin user into robo3T, for example. Using the two commands below poses no issue. However, when I use the listCollections command, I only get the collections from ...

What is the best way to use a computed property as a style value for a component in Vue.js?

My component's template includes the following HTML element: .grid-item(:style="{ width: columnWidth, backgroundColor: 'blue' }") I want to dynamically set the width of this element using a computed property: computed: { columnWidth () ...

Retrieve the numerical worth of a specific offspring component

I am currently working with the following HTML structure: <td class=​"prd-var-price"> ​<div class=​"price-total">​ <span class=​"price-unit">​€​</span> ​<span class=​"price-value">​ ...

What could be causing the empty object return from the Async function in my Typescript code on Next JS?

Encountering issues with an async function. In the ../lib folder, I have a class for handling data from an API website. However, when attempting to load the API data within an async function, I encounter difficulties. The async function does not return a ...

Ensuring that all routes in Express 4 redirect from HTTP to HTTPS

Is there a way to redirect all http:// requests to https:// for every route in my express 4 application? I've tried this method, but it seems to cause a redirect loop error I'm currently utilizing the Express 4 Router in the following manner: ...

What is the syntax for populating an attribute on the same line as v-for in Vue.js?

I am currently working on a simple loop utilizing Vue to iterate over an array of objects and populate table rows. <tr v-for="user in users"> <td>{user.name}</td> <td>{user.id}</td> </tr> However, I also need to as ...

Adding a new entry to a Java file

Hello everyone, I'm currently using jqgrid and wanted to share my file with you all: { "rows":[ {"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"}, {"OrderID":"10249","From ...

Loading Animation for Pages and Tables

I'm experiencing a choppy and sudden transition when switching between two pages that contain tables populated using ng-repeat. Upon loading, the footer is positioned halfway up the page below the table heading until the table loads and the layout adj ...

Execute JavaScript script once when route changes

I'm currently working on a system where I want to ensure that my animation-based JavaScript code only runs once after the route changes. The issue I'm facing is that when switching between pages and returning to the about page, the scripts are ca ...

Laravel 4 Data Cleaning for Improved Security

I am currently utilizing Laravel 4 to establish a RESTful interface for my AngularJS application. Right now, I am looking to update an object within my model named Discount Link. The method I am using involves: $data = Input::all(); $affectedRows ...

In search of a jQuery parser for HTML strings that can accurately parse <a> links and <img> images

Is there a HTML string jQuery parser available, specifically for parsing <a> links and <img> images? Alternatively, I am looking for code that can extract all links and images from a HTML string, which can potentially be very large. For exampl ...

What are some ways I can troubleshoot my contact form?

As someone new to web design, I recently completed my very first site using a combination of HTML, CSS, and a touch of JavaScript. I managed to create a small contact form within the site, but now I'm wondering if there's a way to make it functio ...

What is the best way to trigger Vue lifecycle events for all instances of a component?

I am facing an issue with a vue-component that contains multiple instances of the same child-component. Some of these child-components are only displayed under certain conditions. The problem I am encountering is that when the if-condition becomes false, o ...