Calling a filter from a filter

Hello,

I have a Vue that includes multiple filters. I know that I can chain filters together. However, I’m curious, is there a way to call a filter, from a filter. In other words, I’m trying to do something like this:

<div id="myApp">
  <div>{{ original | myFilter }}</div>
</div>

<script type="text/javascript">
  new Vue({
    el: '#myApp',
    data: {
      original: 'u.s.a.'
    },
    filters: {
      myFilter: function(value) {
        if (!value) {
          return 'N/A';
        }

        value = this.toUpperCase(value);
        return value;
      },

      toUpperCase: function(value) {
        return value.toUpperCase();
      }
    }                
});        
</script>

The code above doesn’t work because I’m calling toUpperCase from myFilter. My question is, is there a way to call a filter from within another filter. Once again, I know I could chain. But, I’m just curious if there’s a way.

this.$options.filters.toUpperCase(value)

1 Like

I tried that approach. However, it didn’t work. I’ve created a JSFiddle to show how it’s not working. That Fiddle is available here: https://jsfiddle.net/8jvnzp1a/1/. What am I doing wrong?

Oh, right - filters are not bound to the current component instance because thy are meant to be pure functions.
So you would have to do some trickery in beforeCreate():

https://jsfiddle.net/Linusborg/8jvnzp1a/2/

You are really working against the intentions of the framework here, so: why?

3 Likes

Just export filter func and use it in filter difinition and any other places by importing it.