1. What is a filter in Vue
Filter ( filter
) is an indispensable device on the transmission medium pipeline. In plain English, it is to filter out some unnecessary things. The filter does not change the original data in essence, but returns the filtered data after processing the data. For call processing, we can also understand it as a pure function.
Vue
Allows you to customize filters that can be used for some common text formatting
ps: Vue3
obsolete infilter
2. How to use the filter in Vue
vue
Filters in can be used in two places: double curly brace interpolation and v-bind
expressions, filters should be added at JavaScript
the end of the expression, indicated by the "pipe" symbol:
define filter
Define local filters in component options
Define a global filter:
Note: When the global filter and the local filter have the same name, the local filter will be used
Filter functions always receive the value of the expression (result of the previous operation chain) as the first argument. In the above example, capitalize
the filter function will receive message
the value of
Filters can be connected in series
In this example, filterA
the filter function is defined to take a single argument, and message
the value of the expression will be passed as an argument to the function. Then go ahead and call the filter function, which is also defined to take a single argument filterB
, filterA
passing the result into filterB
.
Filters are JavaScript
functions and thus can receive parameters:
Here, filterA
is defined as a filter function that accepts three parameters.
The value in it message
is used as the first parameter, the ordinary string 'arg1'
is used as the second parameter, and arg2
the value of the expression is used as the third parameter
for example:
summary:
- Local filters are invoked with precedence over global filters
- An expression can use multiple filters. Filters need to be separated by a pipe character "|". Its execution order is from left to right
3. Filter application scenarios in Vue
In normal development, there are many places that need to use filters, such as unit conversion, digital management, text formatting, time formatting, etc.
For example, if we want to achieve 30000 => 30,000, then we need to use a filter