Using Vuetify to filter items in a v-data-table upon clicking a button

My table structure is similar to this, I am looking to implement a functionality where clicking on the Filter Button will filter out all items that are both male and valid with a value of true.

users = [
    { name: 'ali', male: true, valid: true },
    { name: 'kevin', male: true, valid: false },
    { name: 'meri', male: false, valid: false }
  ]
  get headerst() {
    return [
      {
        text: 'user',
        align: 'start',

        value: 'name'
      },
      {
        text: 'male',
        value: 'male'
      },
      {
        text: 'valid',
        value: 'valid'
      }
    ]
  }
  filterOnlyCapsText(value, search, item) {
    return (
      value != null &&  typeof value === 'boolean' && value===true
    )
  }
  filter(){
  // i dont know
  }
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14626171607d726d54263a6c">[email protected]</a>/dist/vuetify.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<v-btn @click="filter">filter</v-btn>
    <v-data-table
     
      :headers="headerst"
      :items="users"
      item-key="name"
      class="elevation-1"
      :custom-filter="filterOnlyCapsText"
    >
 
 
    </v-data-table>

I have attempted writing code for this but it is not functioning properly.

Any suggestions on how to fix this issue?

This additional text serves no particular purpose other than avoiding stack errors. this text is nothing just to avoid stack error this text is nothing just to avoid stack error this text is nothing just to avoid stack error this text is nothing just to avoid stack error

Answer №1

If you want to achieve this, make sure to modify your filter method to return the following:

return value != null &&
        search != null &&
        typeof value === 'string' &&
        value.toString().toLowerCase().indexOf(search.toLowerCase()) !== -1 && 
        item.male === true && 
        item.valid === true;

This code snippet indicates that from the item, you can access the male and valid properties for comparison. Additionally, the line

value.toString().toLowerCase().indexOf(search.toLowerCase()) !== -1
ensures a match between searched text and value.

To implement a button for filtering only male and valid users, create a computed property named filteredUsers with the following structure:

filteredUsers(){
      if(this.onlyValidAndMale){
        return this.users.filter(user => user.male == true && user.valid == true)
      }
      
      return this.users;
    },

Note the presence of the onlyValidAndMale property here, which should be defined in the data() section.

Once set up, use filteredUsers as a source for :items in your table.

Create a button that toggles the onlyValidAndMale property between true and false on click. Here's an example implementation:

 <v-btn @click="onlyValidAndMale = !onlyValidAndMale">Click here to filter only those that are male and valid.</v-btn>

You can find a complete working example here.

HTML FILE:

<div id="app">
  <v-app id="inspire">
    <div>
      <v-data-table
        :headers="headers"
        :items="filteredUsers"
        item-key="name"
        class="elevation-1"
        :search="search"
        :custom-filter="filterOnlyMaleAndValid"
      >
        <template v-slot:top>
          <v-text-field
            v-model="search"
            label="Search (Will match only male = true and valid = true)"
            class="mx-4"
          ></v-text-field>
        </template>
      </v-data-table>
    </div>
        <v-btn @click="onlyValidAndMale = !onlyValidAndMale">Click here to filter only those that are male and valid.</v-btn>
  </v-app>
</div>

JS FILE:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      search: '',
      onlyValidAndMale: false,
      users: [
    { name: 'ali', male: true, valid: true },
    { name: 'muhamed', male: true, valid: true },
    { name: 'sami', male: true, valid: true },
    { name: 'kevin', male: true, valid: false },
    { name: 'meri', male: false, valid: false }
  ],
    }
  },
  computed: {
    filteredUsers(){
      if(this.onlyValidAndMale){
        return this.users.filter(user => user.male == true && user.valid == true)
      }
      
      return this.users;
    },
    headers () {
      return [
      {
        text: 'user',
        align: 'start',

        value: 'name'
      },
      {
        text: 'male',
        value: 'male'
      },
      {
        text: 'valid',
        value: 'valid'
      }
    ]
    },
  },
  methods: {
    filterOnlyMaleAndValid (value, search, item) {
      return value != null &&
        search != null &&
        typeof value === 'string' &&
        value.toString().toLowerCase().indexOf(search.toLowerCase()) !== -1 && 
        item.male === true && 
        item.valid === true;
    },
  },
})

I also improved the name of the filter method for better clarity, but its functionality remains unchanged.

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

Determine the data type of a property by referencing the data type of another property within an array of objects using TypeScript

I am working with a specific type of interface called Route that consists of name and path properties. interface Route { name: string, path: string } const routes = [ { name: "first", path: "/first" }, ...

What can cause a problem with the reduce function that populates an empty object with keys in TypeScript?

I've encountered an issue with a function that is meant to reduce an object. The problem lies in using the reduce method to assign the values of acc[key] as object[key], which is resulting in errors in the code. I am trying to avoid using any specific ...

Using Vue.js 2 on multiple HTML pages with Typescript and ASP.Net Core

My ASP.Net Core MVC project utilizes VueJs2 for more complex tasks, with each view having its own corresponding js file. The directory structure is as follows: ├ Controllers\HomeController.cs (with actions Index & Details) ├ Scripts\Hom ...

Navigating through different components in Angular 4 using a service for routing

Encountering an issue while connecting my Angular 4 and REST application with a service. Here's the error message: compiler.es5.js:1694 Uncaught Error: Can't resolve all parameters for TypeaheadComponent: (?, [object Object], [object Object]). ...

What is the best way to perform an AJAX request in Typescript with JSON data?

Currently, I am delving into the realm of AJAX and encountering some hurdles when attempting to execute an AJAX request with parameters. Specifically, I am facing difficulties in sending JSON data: My approach involves utilizing Typescript in tandem with ...

Resolving the non-null assertion error in TypeScript and React: A step-by-step guide

My code snippet is as follows: type ItemProps = { status?: string; } <Items status={status!} /> // encountering an error with a warning about forbidden non-null assertion // @typescript-eslint/no-non- ...

Best practice for incorporating the cq-prolyfill third-party JavaScript library into an Angular 5 application

I'm experiencing an issue with the cq-prolyfill library not functioning properly when included through a typescript import statement within an angular module. I have confirmed that it is included in my vendor bundle, but for some reason the initial se ...

Monaco Editor in TypeScript failing to offer autocomplete suggestions

When using a union type as a parameter of a function in Monaco Editor, the suggestions do not appear. However, in VS Code, the suggestions are provided. Is there a setting I need to enable in Monaco to have the same functionality? Although Monaco provides ...

Creating an enum from an associative array for restructuring conditions

Hey everyone, I have a situation where my current condition is working fine, but now I need to convert it into an enum. Unfortunately, the enum doesn't seem to work with my existing condition as mentioned by the team lead. Currently, my condition loo ...

Encountering an issue stating: "[Vuetify] v-ripple can only be applied to block-level elements" while attempting to deploy on Heroku platform

Lately, I've been working on developing an app using Rails 6 with a mix of Vue and Vuetify for the front end. Everything runs smoothly on my local machine. However, as soon as I attempt to deploy it on Heroku, I encounter this error in the debug conso ...

Tips for properly implementing an enum in TypeScript when using the React useState hook

What's the correct way to utilize my useState hook? I have this enum type: export enum Status { PENDING = 'pending', SUCCESS = 'success', ERROR = 'error', } And the useState hook: const [isValid, setIsValid] = use ...

Unveiling the Magic: Displaying Quill's raw HTML in Vue.js

Within my Vue.js app, I am utilizing the Quill editor to generate raw HTML content that is saved directly to the database without any cleaning. When fetching this content from the backend, the text and styling are displayed correctly (colors, bolding, etc. ...

What could be causing the issue of my application not being able to operate on the specified port on Heroku?

After spending two whole days trying to decipher the Heroku error message with no success, I'm still unable to pinpoint what is causing the issue. 2021-07-18T04:27:08.741998+00:00 app[web.1]: {"level":30,"time":1626582428741,&quo ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

React's Redux persist is causing a duplication of requests being sent

I am currently utilizing redux-persist along with Redux Toolkit. I have observed a peculiar behavior where, upon changing the slice (RTK), a request is sent to the server. When using redux-persist without a persister, only one request is made as expected. ...

The enum cannot be assigned a type of 'string | null'

Within my ProductGender enum, I have: enum ProductGender { Men, Women, } In my getProducts service: public getProducts( gender: ProductGender, category: ProductCategory ): Observable<IProductInterface[]> { return this.httpPro ...

tips on retrieving the Vue element using a method in Vue.js

How can I dynamically add an element to the array by clicking a button in vue.js? Is it possible to call the method aggiungiViaggio on click, and how do I determine which viaggio I am currently in? Below is an example of the HTML: <div class=" ...

Ways to determine the overall cost of a shopping cart using Vuejs Vuex

Running a business requires managing various aspects, including tracking the inventory. In my store, I have an array called basketContents that contains items with their respective quantities and prices. An example of how it looks is: state: { basketConte ...

Retrieve the outermost shell of the VUEjs wrapper test-utils

While working on a VueJS test, I encountered an issue where accessing the outermost layer of HTML seemed impossible. No matter what methods I tried, the outermost layer was always ignored. Is there a way to gain access to this outermost layer so that I c ...

When attempting to log a console statement using Vue Axios, an unexpected error occurs and returns an unexpected

My attempt to display jsonplaceholder posts using axios and vue is resulting in an unexpected console output that points back to the console.log statement. Check out the code snippet below: <script> import axios from 'axios'; export d ...