vue.jsvue-componentvue-filter

Explicitly import Vue filters into component


I have a global filters file, and I am trying to explicitly import just one filter into a component.

In my filters file, I have:

//filters.js
import Vue from 'vue';
Vue.filter('shorten', (str, len) => (str.length > len ? `${str.substring(0, len)}...` : str));
Vue.filter('secToMin', (dur) => Math.ceil (dur / 60));

and then in my component, I'd like to do something like:

//MyComponent.vue
import secToMin from './util/filters.js';
export default {
 filters: {
   secToMin: { secToMin, },
 },
};

But this does not actually fire the filters. Is it possible to do something like this??


Solution

  • You can export the filters as named exports:

    export function shorten (str, len) {
      return str.length > len ? `${str.substring(0, len)}...` : str;
    }
    
    export function secToMin (dur) {
      return Math.ceil(dur / 60);
    }
    

    Then in your component:

    import { secToMin } from './util/filters.js';
    
    export default {
     filters: {
       secToMin
     }
    };