What is the best way to implement multiple filters on the data of a Vue component?

I am facing a challenge in implementing multiple filters in a component. For instance, users should be able to choose a category and have the results filtered accordingly. Moreover, with a search filter already in place, I am looking for a way to combine it with other filters like the holiday filter. Specifically, if a user enters 'Winter' in the search field and selects a category that does not include winter (such as holidays), no results should be displayed.

Despite searching on Google, I have only been successful in implementing one filter at a time.

UPDATE I updated my computed properties to utilize a general filteredItems array. Although I am now able to set filters, the issue arises when initially loading the page - nothing appears until a filter is selected. Any suggestions on how to rectify this?

<template>
  <div class="cards">
    <CountdownCard
      v-for="(event, index) in filteredItems"
      :key="index"
      :event="event"
    />
  </div>
</template>

<script>
import CountdownCard from '@/components/CountdownCard'
import EventBus from '@/components/EventBus'

export default {
  components: {
    CountdownCard
  },
  data() {
    return {
      events: [
        {
          title: 'Autum',
          date: 'September 22, 2020',
          emoji: '🍂',
          type: 'holiday',
          year: 2020,
          month: 8,
          day: 22,
          hour: 0,
          minute: 0
        },
        {
          title: 'Winter',
          date: 'December 21, 2020',
          emoji: '⛄️',
          type: 'holiday',
          year: 2020,
          month: 11,
          day: 21,
          hour: 0,
          minute: 0
        }
      updateSearch: ''
    }
  },
  mounted() {
    EventBus.$on('search-countdowns', search => {
      this.updateSearch = search
    })
  },
  computed: {
    filteredItems: function() {
      return this.events
        .filter(event => {
          return event.title
            .toLowerCase()
            .includes(this.updateSearch.toLowerCase())
        })
        .filter(event => {
          return event.type == this.filter
        })
    }
  }
}
</script>

There is also a filteredHolidays filter included, which triggers upon clicking a button to display only holiday-related results.

Below is the button component that, when clicked, is supposed to apply the filter in the first component:

<template>
  <button>{{ filter.name }}</button>
</template>

<script>
export default {
  props: {
    filter: {
      type: Object,
      required: true
    }
  }
}
</script>

Answer №1

Why not simplify the process by creating a single computed property for all filters, known as filteredItems, and then iterate through it in the template.

v-for="(event, index) in filteredItems"

computed: {
    filteredItems: function() {
      return this.events
        .filter(event => {
          return event.title
            .toLowerCase()
            .includes(this.updateSearch.toLowerCase())
        })
        .filter(event => {
          return event.type == this.filter
        })
    }
  }

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

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...

What is the ternary operation syntax for setting the img src attribute in Angular 8?

My data includes a property called "photo" which can either have a file name or be empty. For instance, it could be "steve.jpg" or just an empty string if Steve does not have a photo. In React JSX, I know how to use a ternary operator with the "photo" va ...

Can the SVG def element be modified?

In my SVG file, there is a defs element structured as follows: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 250 330" onclick="tweenGloss()"> <defs> <linearGradient id="grad" x1="174.6 ...

Retrieve the key values from an object of a generic type

Is there a way to retrieve the keys of the object when it is of type T? I attempted to accomplish this using different methods such as: function getGenericTypeKeys<T>(): string[] { return Object.keys({} as T); } and function getGenericTypeKeys< ...

"Is it possible to use a Twitter widget with Mootools

I have been attempting to create a marquee for my twitter Account on my website. After some trial and error, I was able to achieve this using jQuery. Here is the code I used: <div id="twitter"> <p> Loading.....</p> <n ...

Check an image preview prior to uploading through FileReader, rotates the image

After browsing through numerous posts about viewing images before uploading, I stumbled upon an intriguing solution that claimed to be simple using FileReader: function displayImage(input) { if (input.files && input.files[0]) { var reader = ne ...

Troubleshooting issue with Vue Class Component and Vuex-class causing ESLint error

I am interested in utilizing vuex-class to bind helpers for vuex and vue-class-component However, an error message is displayed: Error: Parsing error - Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class ...

Preventing the removal of a choice by disabling it in the selector

I have a unique selector that is designed like this: <select id="patientSelector"> <option disabled selected style='display: none;' id="select0"> New Patients to Come</option> <option id="select1"></opt ...

Issues have been encountered with activating checkboxes on Internet Explorer while utilizing ASP.NET CheckBox controls

I'm facing an issue with an HTML form that includes two disabled checkboxes and an image with an onclick event intended to display a popup and enable the checkboxes: <input id="chk1" type="checkbox" disabled="disabled" /> <input id="chk2" ty ...

The v-on:click functionality seems to have become unresponsive after being dynamically added through modifying the inner

While attempting to create a dynamic navbar, I encountered an issue. The goal was to have the navbar switch from displaying "login" and "register" when a session is logged in, to showing "profile" and "logout". The buttons for login and register were fun ...

Tips for connecting an input tag within a popover to a Vue Model

I've got an input nested inside a popover content as shown below: JSFiddle Link HTML code snippet: <div id="vue-app"> <div class="btn btn-primary" data-toggle="popover" data-placement="bottom" title="Hello World!" data-html="true" data ...

The table width is malfunctioning on Firefox when viewed in HTML

I have been puzzled by the fact that I am unable to adjust the width of the table th in Firefox browser to the smallest value. However, in Chrome browser, this functionality works perfectly. I simply want to divide the values of my td into three rows as sh ...

Using Javascript, delete all chosen HTML elements containing innerText

Looking to extract certain HTML tags from a block of code in TextArea1 and display the modified output in TextArea2 upon clicking a button. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8&quo ...

Fixing the issue: "Tricky situation with JavaScript not working within Bootstrap 4's div tag while JS functions properly elsewhere"

Currently, I'm working on implementing a hide/show function for comments using JavaScript. Fortunately, I was able to find a helpful solution here (thanks to "PiggyPlex" for providing the solution on How can I hide/show a div when a button is clicked? ...

Troubleshooting: The issue with json_encode in Ajax calls

I am facing an issue with my ajax call and the json response. The console is indicating that my php file is not returning a json format, but I am unable to pinpoint the exact reason behind it. Below is my ajax function: function showEspece(espece, categori ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

The Jquery AjaxStop event fails to trigger, but AjaxStart works perfectly

While I was working with APIs, I encountered a roadblock. I have a Jquery function that retrieves data from an API. To prevent a "reposition" effect, I need the function to wait until all calls are made before triggering another function to place all the ...

Tips for preventing text from changing its padding within a div when reducing the width and height dimensions

I am facing an issue with a div inside another div. The child div contains text, and when I apply animation to decrease the width and height, the text inside gets reset according to the new size. While I understand why this happens, I want to find a way to ...

What is the process for encrypting and decrypting image files over the internet?

I'm currently developing a web application that requires loading images into a canvas object, followed by extensive manipulation. My goal is to conceal the original source image file (a jpeg) in such a way that users on the client side cannot access i ...

Avoid showing an image when it is outside the div container

Within a single div, I have an assortment of images that are dynamically repositioned using JQuery. $("#"+carElem).css({"left": pos.left+50 +"px"}); I am currently utilizing absolute positioning (although relative positioning yields the same outcome). Is ...