DEV Community

Firmino Changani
Firmino Changani

Posted on

Accessing vue global filters inside component methods

Often times you will need to access the global filters in from your vue app inside methods and lifecycle within components. Well it's possible to do that without hacks and crazy imports, instead you'll use the $options object:

this.$options.filters.yourFilterName(paramValue);
Enter fullscreen mode Exit fullscreen mode

Demo

Let's suppose you have a global filter in your main.js that formats regular Numbers into the USD currency format, you'll would have something like this:

// main.js
import Vue from "vue";

/**
 * numberToUSD: It format numbers into the USD currency format.
 * @param {number} value
 * @returns {string} value
 */
Vue.filter("numberToUSD", value => { 
    return value ? `$${value.toLocaleString("en-US")}` : "$0.0";
});
Enter fullscreen mode Exit fullscreen mode

And then you want to access this same filter inside of a component method or lifecycle method, using the $options object would be something like:

// App.vue

export default {
    name: "App.vue",
    data() {
        return {
            value: 5000
        };
    },
    methods: {
        /*
         * Inside a regular method
         */
        logValueInUSD() {
            console.log(this.$options.filters.numberToUSD(this.value));
        }
    },
    /**
     * Inside lifecycle method: created()
     */
    created() {
        console.log(this.$options.filters.numberToUSD(this.value));
    }
}
Enter fullscreen mode Exit fullscreen mode

This technique became pretty handy to me specially when I needed to pass value as props to a third-party component where I couldn't apply them using interpolation and pipes {{ value | numberToUSD }}.

The only downside that I noticed while accessing global filters through $options was that the instructions to access the filter may become a little bit longer, but this could be easily overcome by wrapping up the this.$options.filters into a variable and then access the specific filter just like this:

const filters = this.$options.filters;

filters.numberToUSD(this.value);
Enter fullscreen mode Exit fullscreen mode

Thanks for having you here, bye bye 👋👋.

Top comments (1)

Collapse
 
dannons profile image
Daniel Hobson

Is there a benefit to this method over using a mixin? I've just started learning Vue so may be missing something