Global Filters
Migrating Global Filters to Vue 3 alternatives
Introduction
Filters have a complicated history in Vue They were quite beloved in Vue 1, but also proved to be as n on the maintainer side, as they are pretty much the only part of Vue's template syntax that is not interpretable as Javascript expressions.
<template>
<p>$ {{ product.price | asCurrency }}</p>
</template>
They also suffered from ambiguity (when to use a filter, when to use a method, or computed property?) and were limited to be used in templates, not really accessible in the JAvascript code of your components.
So in Vue 2, their use was further limited, and now in Vue 3, they are completely gone. They were usually registered globally with Vue.filters()
and then used as little helpers al throughout an app, to properly format values for display, for example.
This means we have to take care of two things for our migration to Vue 3:
- Find an alternative pattern to registering filters globally with
Vue.filter()
- Replace all filters syntax with an alternative
Then, in Vue 2
Our app runs a pretty typical setup to use filters. We have a filters.js
file that contains all of your filter functions, and we register them with Vue.filter()
. Then we import that file into main.js
and our filters are ready to be used in all of our component templates.
import Vue from 'vue'
function inCaps(value) {
return value.toUpperCase()
}
Vue.filter('inCaps', inCaps)
import './filters'
// rest of the code omitted
Usage Example:
<li v-for="todo in todos" :key="todo">{{ todo | inCaps }} !!!</li>
Migrating to Vue 3
Using the plugin function pattern
If you carefully read the previous chapters about components and directives, you're already familiar with our first step: We create and a plugin function that receives our app
instance as its only argument:
function inCaps(value) {
return value.toUpperCase()
}
+ export function addFilters(app) {
+ const filters = {
+ inCaps: inCaps,
+ }
+
+ // ... but how do we "register" filters?
+ }
- Vue.filter('inCaps', inCaps)
globalProperties
Using Vue 3 no longer has filters, so of course there is no app.filter
- but we can make the filters available to all our through a global property.
function inCaps(value) {
return value.toUpperCase()
}
export function addFilters(app) {
const filters = {
inCaps: inCaps,
}
app.config.globalProperties.$filters = filters
}
This will make a $filters
property available in all components within our app.
<li v-for="todo in todos" :key="todo">{{ $filters.inCaps(todo) }} !!!</li>
The upside of this is that we can now easily use filters in our Javascript as well through this.$filters