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

My table structure is similar to this, https://i.sstatic.net/56TUi.png 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

Having trouble displaying data on Firebase with V-data-table in Vue.js?

I'm encountering an issue with displaying data from Firebase on a v-data-table. Below is my code snippet: <template> <div class="dashboard"> <h2 class="subheading mx-5">Subject</h2> <v-btn block color="primary mt- ...

Can a component be passed as props and utilized within a child Component in Vue.js?

If we have components A, B, and C in a Vue 2.0 app, A declares, registers, and uses B. Can we pass C from A to B? For example: <template> <div class="A"> <B :child_component="C" /> </div> </template ...

Passing properties to a component from Material UI Tab

I have been attempting to combine react-router with Material-UI V1 Tabs, following guidance from this GitHub issue and this Stack Overflow post, but the solution provided is leading to errors for me. As far as I understand, this is how it should be implem ...

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Utilizing Next.js to Import a Function from a Path Stored within an Environment Variable

I'm having trouble importing a function whose path is stored in an environment variable Current import statement: import { debug } from '../lib/site-A/utils' Expected import statement: import { debug } from process.env.DEBUG_PATH In my ...

Exploring the generalization of class member initialization in TypeScript

I am looking to make some modifications to the Blog constructor provided in the "Minimal working example" linked below. The objective is to refactor it using pseudo-code by leveraging a generic ModelHelper class to initialize the members of the "Blog" clas ...

Vue.js 2 - Sending events from one Vue application instance to another: A step-by-step guide

I am currently using webpack along with Single File Components. Within my project, I have two instances of Vue being utilized. One instance is integrated into the menu header to display a Cart Shopping dropdown: import Vue from 'vue'; import App ...

Enhance autocomplete functionality by incorporating a left icon feature for text fields within the autocomplete component

I have a component with autocomplete functionality that displays tags Autocomplete with tags and I am trying to add a left icon, but only the right icon is functioning correctly. Current Issue When I add a left icon, it shows up but prevents the renderi ...

Unlocking the capabilities of Chrome extensions using Angular 2 and TypeScript

Currently attempting to develop a chrome extension using angular2 and typescript, I have hit a roadblock in trying to access the chrome API (in this case, chrome.bookmarks). I have successfully gained access to the chrome object by following guidance from ...

Having trouble getting tsserver-plugins to function properly in either Atom or VSC

My team and I are on a mission to enhance our Angular 2 templates with code completion, similar to what is showcased in this gif. To achieve this goal, we require: tsserver-plugins coupled with tslint-language-service and @angular/language-service We ...

The specified file cannot be found within the Node file system

I am working on a project that involves reading a file using Node fs, and I have the following code: const files: FileSystemTree = { "Component.tsx": { file: { contents: fs.readFileSync( `../../apps/components ...

What is the correct way to convert a non-observable into an observable?

Can I convert a non-observable into an observable to receive direct image updates without having to refresh the page, but encountering this error: Type 'EntityImage[]' is missing the following properties from type 'Observable<EntityImage ...

Issue with Ionic Capacitor React & Typescript build process for Firebase Functions

Recently, I've been working on a cutting-edge Ionic Capacitor React application that utilizes Typescript with a Firebase backend. While everything has been running smoothly so far, I encountered some challenges when trying to build Firebase Functions. ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Creating a dynamic v-if component with Vue.js

I am facing a challenge in making my component reactive. Although the button is rendered correctly, the template does not update after the create/delete event. Any suggestions on how to refresh the component post-event? new Vue({ el: '#app' }) ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

The @click function does not function properly when employing runtimeConfig in Nuxt 3

Here is a demonstration I created: https://stackblitz.com/edit/github-jsuxnz-rst5gg-git?file=app.vue Initially, the @click function works fine until I introduce runtimeConfig with const config = useRuntimeConfig();, after which all events cease to work. ...

Dynamically generate <router-link> elements by iterating over routes with Vue-router

I'm looking to iterate over my routes using v-for to dynamically create <router-link>s in the template section. Currently, I'm unsure how to access the router parameter, defined in main.js, within the template section of my jvds-navigation ...

The data type 'boolean' cannot be assigned to the type 'StoryFnReactReturnType' in a React Storybook project using Typescript

I am currently working on setting up a Button component with Storybook in typescript. I am referencing The Documentation and using this specific example. Below is my Component and its story: components/Button.tsx: import {FC} from 'react'; exp ...

Validating React Typescript Props: Ensuring that two specific props do not exist simultaneously

Currently, I'm developing a reusable component in React-Typescript and I am looking to validate my props OnClick and component as follows: Both onClick and component prop are optional. These props will only be passed to the component if they need to ...