43

I want to make use of a few global filters in a Vue.js app. I know I need to define them before my main Vue instance, but sticking them all in the 'main.js' file doesn't seem right to me from a code organisation point of view. How could I have the definitions in a separate file, imported to 'main.js'? Can't quite get my head around the import/export stuff for this.

4 Answers 4

79

Create a filters.js file.

import Vue from "vue"

Vue.filter("first4Chars", str => str.substring(0, 4))
Vue.filter("last4Chars", str => str.substring(str.length - 4))

Import it into your main.js.

import Vue from 'vue'
import App from './App'
import "./filters"

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
})

Here is a working example.

Side note: If you get a "Vue not found" type of error, as a test try importing filters after the new Vue() declaration, like this:

import Vue from 'vue'
import App from './App'

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
})

import "./filters"
3
  • As simple as that! Thanks.
    – John Moore
    Commented Oct 30, 2017 at 9:06
  • when I named the file filter.js I had to use import "./filter"
    – thedanotto
    Commented Aug 21, 2018 at 3:16
  • 1
    good answer, for better reading I make a folder called filter and write the filter in a file filter/index.js than you can import ./filters.
    – Milan
    Commented Nov 8, 2018 at 15:24
41

I think the best way is to use the pluginfeature from VueJS

  1. Create a filters folder and put all of you filters there ...

    - filters
      | - filter1.js
      | - index.js
    
  2. In the filter file export the function you need, in this example I'll use a uppercase filter:

    export default function uppercase (input) {
        return input.toUpperCase();
    }
    
  3. In the index.js import and create a plugin:

    import uppercase from './filter1';
    
    
    export default {
         install(Vue) {
             Vue.filter('uppercase', uppercase);
         }
    }
    
  4. In you main.js file use it

    import filters from './filters';
    import Vue from 'vue';
    
    Vue.use(filters);
    
2
  • 3
    this feels more neatly contained than calling Vue.filter(...) in each filter definition file
    – plong0
    Commented Sep 27, 2018 at 5:31
  • I had trouble getting this to work with my application and realized that Vue evaluates conditional expressions differently in the HTML template than Angular does. Proper syntax for this would be {{ value ? $options.filters.uppercase(value, 'params) : '--' }} Commented Nov 22, 2019 at 20:43
7

What I like to do is

  1. Have a filter per file (es6 module)

  2. Register the filter globally with vue in the module

  3. Also export the filter function as the default export

For example for a simple filter that puts comma separators in numbers I create NumberFilter.js and NumberFilter.test.js

NumberFilter.js

import Vue from 'vue';
import numeral from 'numeral';

const NumberFilter = number => numeral(value).format('0,0');

Vue.filter('number', numberFilter);

export default numberFilter;

NumberFilter.test.js

import NumberFilter from './NumberFilter';

describe('NumberFitler', () => {
   it('exists', () => {
      expect(NumberFilter).toBeDefined();
   });

   it('does its thing', () => {
       expect(NumberFilter(1234)).toEquals('1,234');   
   });
});

This strategy allows me to use this filter in code as a standard es6 module and as well as in my Vue templates.

In the real world I would probably mock numeral in my test and just make sure the result of .format was called with the correct number format.

7

[Vue mixins][1] could be used to add global filters, filters can setup in a file and then import filters file in main.js file.

filters.js

export default{
    firstWordCapitalize (value) => {
        if (!value)
            return ''
        value = value.toString()
        return value.charAt(0).toUpperCase();
    },
    anotherFilter(value) =>{
      return value+"-test";
    }
}

main.js

import Vue from 'vue';
import Filters from './filters';
Vue.mixin({
  filters: Filters
});

And you can use filters in any template. [1]: https://v2.vuejs.org/v2/guide/mixins.html

1
  • 1
    VueJS official docs warn against overusing global mixins because they get injected into EVERY instance of Vue that gets created.
    – omarjebari
    Commented Apr 21, 2020 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.