In Vue.js how do I write custom filters in separate file and use them in various components by declaring in main.js?

Here's an example:

// MyFilter.js
import Vue from 'vue';

Vue.filter('myFilter', value => {
  return value.toUpperCase();
});
// main.js
import './MyFilter.js';

If you don't want to register the filters globally, you can do it like this:

// MyFilter.js
export default function (value) {
  return value.toUpperCase();
}
// MyComponent.vue
import MyFilter from './MyFilter.js';

export default {
  filters: {
    MyFilter,
  },
};

If you don't have so many filters, you can also define them in a single file:

// filters.js
export default {
    filterA: () => {},
    filterB: () => {},
}

And import them globally:

// main.js
import filters from './filters';
for(let name in filters) {
    Vue.filter(name, filters[name]);
}

Tags:

Vue.Js