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

Viewed 12825

I tried doing this, but it does not work.

// filter.js

export default {
    converTimestamp: function (seconds) {
      var date = new Date(seconds * 1000);
      return date.toDateString();
    }
};

// main.js

import customFilters from './store/filters';
3 Answers

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]);
}

We can create a plugin for that:

// filters.js
import Vue from 'vue'

export function truncate( text, length, suffix = '...' ) {
    if (text.length > length) {
        return text.substring(0, length) + suffix;
    } else {
        return text;
    }
}

export function json( value ) {
    return JSON.stringify(value);
}

const filters = { truncate, json }

Object.keys( filters ).forEach( key => {
    Vue.filter( key, filters[ key ] )
})

then add this new plugin in the config

export default {
  plugins: ['~/plugins/filters.js']
}
Related