Custom Filters
The Basics
Similar to custom directives, you can register a custom filter with the global Vue.filter()
method, passing in a filterID and a filter function. The filter function takes a value as the argument and returns the transformed value:
1 | Vue.filter('reverse', function (value) { |
1 | <!-- 'abc' => 'cba' --> |
The filter function also receives any inline arguments:
1 | Vue.filter('wrap', function (value, begin, end) { |
1 | <!-- 'hello' => 'before hello after' --> |
Two-way Filters
Up till now we have used filters to transform values coming from the model and before displaying them in the view. But it is also possible to define a filter that transforms the value before it is written back to the model from the view (input elements):
1 | Vue.filter('currencyDisplay', { |
Demo:
Model value: {{money}}
Dynamic Arguments
If a filter argument is not enclosed by quotes, it will be evaluated dynamically in the current vm’s data context. In addition, the filter function is always invoked using the current vm as its this
context. For example:
1 | <input v-model="userInput"> |
1 | Vue.filter('concat', function (value, input) { |
For this simple example above, you can achieve the same result with just an expression, but for more complicated procedures that need more than one statement, you need to put them either in a computed property or a custom filter.
The built-in filterBy
and orderBy
filters are both filters that perform non-trivial work on the Array being passed in and relies on the current state of the owner Vue instance.
Alright! Now it’s time to learn how the Component System works.