loading...

Multiple usage of custom filters in Vue.js

bibhuticoder profile image Bibhuti Poudyal ・2 min read

A Vue.js filter is simply a function that takes an input, processes it and gives an output. Inside a Vue template it is written after a single pipe and can also be followed by its arguments.

Example of Vue.js filter

<span v-html="timestamp | formatDate"></span>
<span> Also like this: {{timestamp | formatDate}} </span>

But there can be some particular case where the filter functions are required to be used outside directive and mustaches. This article will show a simple mechanism to tackle the problem.


A custom filter can be registered either globally or inside components. Since we are doing it the best way, we will be registering it globally.
If you have many filters, its best to keep it on a separate folder inside separate files. For this particular case, I have kept it inside /src/filters.js

Folder Structure

Now lets take a look inside filters.js file.

import Vue from 'vue'
import moment from 'moment';

export const FILTERS = {
    formatDate: (value) => {
        return value ? moment(value, "x").format("DD MMM YYYY") : '';
    },

    ellipsis: (value, MAX_LEN) => {
        if (value) return value.length > MAX_LEN ? (value.slice(0, MAX_LEN) + '...') : value;
        return null;
    },
}

export const registerFilters = function () {
    Object.keys(FILTERS).forEach(key => {
        Vue.filter(key, FILTERS[key]);
    })
}

As you may have noticed, the FILTERS object contains all of your filter functions. The key serves as filterId and the value as filter function

The file exports two things

  • FILTERS object
  • registerFilters function

That’s the main point. The registerFilters function registers all of the filter functions globally so that it can be used on any Vue component. The method is called inside the main.js file.

// Filters
import { registerFilters } from "./filters";
registerFilters();

Another cool thing about this approach is the ability to import those filter functions and use inside JavaScript logic.

<script>
    import { FILTERS } from "@/filters";

    export default{
        name: 'TestComponent',

        methods:{
            testMethod(){
                let date = new Date();
                return FILTERS.formatDate(date);
            }
        }
    }
</script>

In many cases filter functions need to be used outside of directive and mustaches. This approach works best to handle this particular scenario. Moreover, it groups the filter functions at one place and makes a clear separation of logic inside vue application.

Happy Coding !

Posted on by:

bibhuticoder profile

Bibhuti Poudyal

@bibhuticoder

Co-founder at TheValueCrew. Creator of ramroCode

Discussion

pic
Editor guide