Donnie
Donnie

Reputation: 6351

Apply Filters Programmatically in Vue.js Component

Is it possible to apply filters to select values programmatically? As you can see, I am iterating each record, and then each column. I am checking that the column.id starts with d, which means it's a datetime, so I'd like to apply the humanize filter to only that field. The result of the code you see here is NaN on every field.

<tr v-for="record in records" @dblClick="readRecord(record)">
  <td v-for="column in columns">
    {{ _.startsWith(record[column.id], 'd') ? record[column.id] | humanize : column.id; }}
  </td>
</tr>

Upvotes: 1

Views: 1153

Answers (2)

alex23
alex23

Reputation: 363

You can call your filter in here: this.$options.filters.humanize

Upvotes: 1

Roy J
Roy J

Reputation: 43881

That's getting kind of code-thick for the view. It would be better to make a method that does that (particularly since filters are deprecated -- [update] only filters in directives are deprecated).

new Vue({
  el: '#app',
  data: {
    columns: [{
      id: '1'
    }, {
      id: '2'
    }],
    record: {
      2: 'dthing'
    }
  },
  methods: {
    displayCol: function(col) {
      if (s.startsWith(this.record[col.id], 'd')) {
        return this.humanize(this.record[col.id]);
      }
      return col.id;
    },
    humanize: function(recVal) {
      return `HUM${recVal}`;
    }
  }
});
<!--script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script-->
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.min.js"></script>
<div id="app">
  <div v-for="column in columns">
    {{displayCol(column)}}
  </div>
</div>

Upvotes: 1

Related Questions