如何在 vuetify 的数据表中使用“自定义过滤器”属性?或如何创建自定义过滤器以按标头进行过滤?

2023-12-20

截至发布日期,我找不到任何在数据表中使用“自定义过滤器”道具的文档。

我只想创建一个自定义过滤器来按标题过滤我的数据表。 我有一个下拉列表,当用户单击下拉列表的选项之一时,它将过滤列表中的一个特定标题。

例子: 下拉选项: 食物类型:水果、肉类、蔬菜

  1. 小白菜(蔬菜)
  2. 猪肉)
  3. 鸡大腿(肉)
  4. 西瓜(水果)

如果我选择下拉菜单作为肉类,它应该只显示猪肉和鸡大腿。


Looking at the code on Github1, it looks like the customFilter prop is used to overwrite the default method used to determine how the filter prop is applied to the items in the table.

默认customFilter方法应用了filter函数对每个项目对象的每个属性名称进行过滤,并过滤掉不包含通过过滤器的属性名称的任何项目:

customFilter: {
  type: Function,
  default: (items, search, filter) => {
    search = search.toString().toLowerCase()
    return items.filter(i => (
      Object.keys(i).some(j => filter(i[j], search))
    ))
  }
},

如果您想防止任何列包含在过滤器中,或者如果您始终希望防止过滤掉某些特定行,您可能需要覆盖此函数。

您会注意到该方法还取决于searchprop,它必须是一个字符串。


话虽如此,您确实不需要使用该道具来完成您想做的事情。您应该只创建一个计算属性来根据下拉值过滤项目,并将该计算属性作为items prop.

这是一个例子:

new Vue({
  el: '#app',
  data() {
    return {
      food: [
        { name: 'Bakchoi', type: 'vegetable', calories: 100 },
        { name: 'Pork', type: 'meat', calories: 200 },
        { name: 'Chicken Thigh', type: 'meat', calories: 300 },
        { name: 'Watermelon', type: 'fruit', calories: 10 },
      ],
      headers: [
        { text: 'Name', align: 'left', value: 'name' },
        { text: 'Food Type', align: 'left', value: 'type' }, 
        { text: 'Calories', align: 'left', value: 'calories' },
      ],
      foodType: null,
    };
  },
  computed: {
    filteredItems() {
      return this.food.filter((i) => {
        return !this.foodType || (i.type === this.foodType);
      })
    }
  }
})
<script src="https://unpkg.com/[email protected] /cdn-cgi/l/email-protection/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected] /cdn-cgi/l/email-protection/dist/vuetify.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected] /cdn-cgi/l/email-protection/dist/vuetify.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">

<div id="app">
  <v-app>  
    <v-select 
      label="Food Type" 
      :items="['vegetable', 'meat', 'fruit']"
      v-model="foodType"
    ></v-select>
    
    <v-data-table 
      :headers="headers"
      :items="filteredItems"
      hide-actions
    >
      <template slot="items" scope="{ item }">
        <td>{{ item.name }}</td>
        <td>{{ item.type }}</td>
        <td>{{ item.calories }}</td>
      </template>
    </v-data-table>
  </v-app>
</div>

  1. 这个答案是在 Vuetify v0.15.2 时写的。的源代码VDataTable该版本的组件可以在这里找到 https://github.com/vuetifyjs/vuetify/blob/8e3eec8ae0ed4f078693109bd7659d359e69979b/src/components/VDataTable/VDataTable.vue.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 vuetify 的数据表中使用“自定义过滤器”属性?或如何创建自定义过滤器以按标头进行过滤? 的相关文章

随机推荐