vue.jsvue-filter

Vue2: Can I pass an optional (global) filter into a reusable component?


I am quite new to Vue. I am working on a table as component, which is supposed to be a lot of times. So far, so good, but now I want to use a filter, which can be optional passed into it.

That is how I "call" the table:

  <table
    :headers="headers"
    :items="some.data"
  ></table>

 data () {
    return {
      headers: [
        { title: 'date', value: ['date'], filter: 'truncate(0, 10, '...')' },
      ]
    }
  }

Here is my table component

    <template>
<div>
  <table class="table">
    <thead>
      <tr>
        <!-- <th v-for="header in headers" :key="header.id" scope="col">{{ header.title }}</th> -->
        <th v-for="header in headers" :key="header.id" scope="col">
          {{ header.title }}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="item in items" :key="item.id" scope="col">
        <td v-for="header in headers" :key="header.id" scope="row">
          <!-- {{item}} -->
          <span v-for="val in header.value" :key="val.id">
             {{item[val] | truncate(0, 10, '...') }}
          </span>
            <!-- {{header.filter}} -->
        </td>
      </tr>
    </tbody>
  </table>
  </div>
</template>

<script >


export default {
  name: 'Table',
  props: {
    headers: Array,
    items: Array
  }
}
</script>

My global filter:

Vue.filter('truncate', function (text, start, truncLength, clamp = '') {
  return text.slice(start, truncLength) + clamp
  // return text.slice(0, stop) + (stop < text.length ? clamp || ' ...' : '')
})

I was hopping, to add by that an optional filter (via v-if I would chech for it). So far I can render the filter as string ... but not execute it.

Even if I put the filter in the span, it does not work (it says then, "text.slice is not a function" in the console.

I was not successful with googling it, because with filters/filter it is mostly about how to use .filter(...) on data as JS method, but not as Vue filter.

Any advise?


Solution

  • A filter is a function that runs inside JSX template in html. Example of how to create custom Vue.js filter

    Vue.filter('ssn', function (ssn) { // ssn filter
                return ssn.replace(/(\d{3})(\d{2})(\d{4})/, '$1-$2-$3');
            });
    

    Using it

    {{stringToTrans | ssn}}
    

    To use a filter outside this you can use a computed property or standard function like so

    convertedDateString() { // computed
       return this.$moment(this.dateString).format('MM/DD/YYYY')
    }
    
    convertedDateString(dateString) { // method
       return this.$moment(dateString).format('MM/DD/YYYY')
    }