How does the vue pass a filter to the child component (the parent component needs to specify the filter that the child component needs to call)?

encapsulates a table component , and the parameters have column header array , which defines the fields to be bound. The problem now is that I need to pass a filter to the table component, passing the filter name of the String type, but how to use this filter in the subcomponent?

the idea is that the parent component defines the columns that need to be displayed and the table data that needs to be displayed. But the column has many properties, such as the bound field, what filter to use, and so on; the subcomponents are displayed according to the property definitions of different columns.

this is a custom component myTable

    name: "myTable",
    props: {
        tabHeades: Array,
        tabDatas: Array,
    },
    methods: {
        //filterName 
        //val 
        dynamicFilter(filterName, val) {
            //
            let filterObj = this.$options.filters[filterName]
            //
            return filterObj(val)
        }
    },    
// {{ xxx | yesOrNo }} 
<span v-if="head.filter">{{ dynamicFilter(head.filter, scope.row[head.key]) }}</span>

call (parent) component: (few columns need to be passed, different columns may need to specify different filter)

    tabHeades: [
        {label: "", key: "id", isHidden: true},
        {label: "", key: "IsShow", filter: "yesOrNo"},//

    ],

at present, this code can achieve the desired results.

but the writing in the sub-component feels so ugly. I hope {{xxx | yesOrNo}} can be used in the sub-component to use the filter. How can I modify it?


Why not consider registering filters globally?

< hr >

Update a wave
in fact, the filter of Vue can pass parameters. You can define the filter like this

Vue.filter('filter', function(val, name){//
  console.log(val, name)
    switch(name){//switch
      case 'filter1': 
        return filter1(val);
      case 'filter2': 
        return filter2(val)
    }
})
// 
function filter1(val){
  return val +  ': filter1'

}
function filter2(val){
  return val +  ': filter2'
}

if you then use it, just enter the filter name

<template>
    <div>
        {{'hahaha' | filter(filter)}}
    </div>
</template>

<script>
export default {
    props: ['filter']
}
</script>

Why not use mixin? It would be nice to write a mixin, where to quote it.

Menu