filter


Filters can be used in two places: double brace interpolation and v-bind expressions (the latter is supported since 2.1.0) . Filters should be added at the end of the JavaScript expression, indicated by the "pipe" symbol:

<!-- 在双花括号中 -->
{{ message | capitalize }}

<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>

You can define local filters in a component's options:

filters: {
  capitalize: function (value) {
    if (!value) return ''
    value = value.toString()
    return value.charAt(0).toUpperCase() + value.slice(1)
  }
}

or when creating Define the filter globally before the Vue instance:

Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})
new Vue({
  // ...
})

When the global filter and the local filter have the same name, the local filter will be used.

The following example uses the capitalize filter:

2.gif

The filter function always receives the value of the expression (the previous operation chain the result) as the first parameter. In the above example, the capitalize filter function will receive the value of message as the first parameter.

Filters can be concatenated:

{{ message | filterA | filterB }}

In this example, filterA is defined as a filter function that receives a single argument, the expression message The value will be passed into the function as a parameter. Then continue to call the filter function filterB, which is also defined to receive a single parameter, and pass the result of filterA to filterB.

Filters are JavaScript functions, so they can receive parameters:

{{ message | filterA('arg1', arg2) }}

Here, filterA is defined as a filter function that receives three parameters. Among them, the value of message is used as the first parameter, the ordinary string 'arg1' is used as the second parameter, and the value of the expression arg2 is used as the third parameter. .