如何在 vuetify 的数据表中使用“自定义过滤器”道具?或如何创建自定义过滤器以按标题过滤?

新手上路,请多包涵

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

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

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

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

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

原文由 alwayshungryleh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 427
1 个回答

查看 Github 1上的代码,看起来 customFilter 用于覆盖用于确定 filter 如何应用于表中的项目的默认方法。

默认的 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))
>     ))
>   }
> },
>
> ```

如果您想阻止任何列包含在过滤器中,或者如果您一直希望阻止过滤掉特定行,则可能需要覆盖此函数。

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

* * *

话虽如此,你真的不需要使用那个道具来做你想做的事。您应该只创建一个计算属性来根据您的下拉值过滤项目,并将该计算属性作为 `items` 属性传递。

这是一个例子:

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); }) } } })


<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>

“`


  1. 这个答案是在 Vuetify 在 v0.15.2 时编写的。 可以在此处找到该版本的 VDataTable 组件的源代码

原文由 thanksd 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题