Filters in Vue.js
Very similar to AngularJs, we have filters in Vue.js in order to deal with recurrent text formatting.
Very similar to AngularJs, we have filters in Vue.js in order to deal with recurrent text formatting tasks.
There are 2 ways you can have filters in Vue.js.
- Local Filters: Filters that are not commonly used, you can register them in the component they are used in.
Vue.component('some-component', {
...filters: {
capitalize: function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
})
- Global Filters: Filters that are commonly used throughout the application, should be registered in the Global scope, so they are available for use from anywhere in the application.
Important: You have to define the Global filters before creating the
Vue instance.Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})new Vue({
...
})
Custom Arguments:
You can pass custom arguments to a filter, apart from the value argument which is by default the first argument. See the example below.
Vue.filter('formatDate', function (value, format) {
if (!value) return ''
return moment(String(value)).format(format);
})
Important: The syntax for passing arguments to filters differs from angularjs{{ someDate | formatDate('DD-MM-YYYY HH:mm') }}
Chaining:
Very similar to Angularjs filters, Vue.js filters can also be chained.{{ someField | filterA | filterB }}
Code Structure — Best Practice for Global Filters:
In most cases we use global filters to perform the recurring formatting tasks. And as mentioned above the global filters in Vue.js needs to be registered before creating the Vue instance.
Everyone has its own style of organizing the code. What I prefer is to create a separate folder for the filters. and add an index.js file to it in order to import all the filters within this folder.- views
- store
- router
- filters
- filterA.js
- filterB.js
- index.js
- main.js
and then you can export it and import it in the main.js before creating the Vue instance.
example index.js
import filterA from "./filterA";
import filterB from "./filterB";export default {};
example main.jsimport Vue from "vue";
import filters from './filters';
new Vue({
...
})
For more information on filters checkout the official Vue.js documentation on filters here.