The use of filter in vue


1. Concept

Vue.js allows us to customize filters, which can be used for some common text formatting. Filters can be used in two places: double braces interpolation and v-bindexpression (the latter is supported from 2.1.0+). The filter should be added at the end of the JavaScript expression, represented by the "pipe" |symbol:

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

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

Two, use

The filter function always receives the value of the expression (the result of the previous operation chain) as the first parameter.

1. Define a global filter

//这个过滤器用于将首字母大写
Vue.filter('capitalize', function (value) {
    
    
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

new Vue({
    
    
  el: "#app",
  data: {
    
    
    message: "hello"
  }
})
<div id="app">
  <!--Hello-->
  <h2>{
   
   {message | capitalize}}</h2>
</div>

2. Define a local filter in the component

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

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

3. The filter can be connected in series

{
    
    {
    
     message | filterA | filterB }}

In this example, it filterAis defined as a filter function that receives a single parameter, and the value of the expression message will be passed into the function as a parameter. Then continue the same call is defined as a single argument and the filter function filterB, and filterAthe result is transmitted to filterBthe.

new Vue({
    
    
  el: "#app",
  data: {
    
    
    message: "hello"
  },
  filters: {
    
    
    addMessage(value) {
    
    
      return value + ' webchang';
    },
    addMessage2(value) {
    
    
      return value + ' world!';
    }
  }
})
  <!--  hello webchang world! -->
  <h2>{
   
   {message | addMessage | addMessage2}}</h2>

4. The filter can receive parameters

The filter is a JavaScript function, so it can receive parameters

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

filterAIt is defined as a filter function that receives three parameters. Wherein the message value as the first parameter, plain string 'arg1'as a second argument, the expression arg2value as the third parameter.

new Vue({
    
    
  el: "#app",
  data: {
    
    
    message: "hello"
  },
  filters: {
    
    
    addMessage3(value, arg1, arg2) {
    
    
      return value + arg1 + arg2;
    }
  }
})
<!--  hello111 你好啊 -->
<h2>{
   
   {message | addMessage3(111,' 你好啊')}}</h2>

3. Information

Filter — Vue.js official website

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/113092438