Basic use of Vue filters - case conversion of initial letters, string splicing

Posted by jonybhi on Mon, 17 Jan 2022 15:55:29 +0100

Filter basic syntax

Vue.filter( id, [definition] )[1]

  • "Parameters":
    • {string} id
    • {Function} [definition]
  • Usage: Register or get global filters.
    // register
    Vue.filter('my-filter', function (value) {
      // Returns the processed value
    })

    // getter to return the registered filter
    var myFilter = Vue.filter('my-filter')

Introduction to the official website of the filter

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

<!-- In double curly braces -->
{{ message | capitalize }}

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

You can define local filters in the options of a component:

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

Or define filters globally before creating Vue instances:

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 local filter have the same name, the local filter is adopted.

The following is an example of converting lowercase letters to uppercase letters on the official website to provide the source code for step-by-step explanation. Several examples will be provided later:

  • Replace splice instance with filter string
  • Time format conversion instance using filter

Instance: capitalize an instance that converts the first lowercase letter to uppercase

1. Definition of local filter:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--  1.Import vue.js library  -->
    <script src="lib/vue.js"></script>

</head>
<body>

<div id="app">

    <!-- 1.Define an input box using v-model The binding input value is msg   -->
    <input type="text" v-model="msg">

    <!-- 2.set up p Note rendering msg Data, that is, when the input box is filled with information, then p The labels are rendered synchronously   -->
    <p>{{ msg | capitalize }}</p>

</div>

<script>
    // 2. Create an instance of Vue
    var vm = new Vue({
        el: '#app',
        data: {
            msg: "" // Defines the msg used to pass data
        },
        methods: {},
        filters:{ // Define local filters

            // Defines a filter for converting lowercase characters to uppercase letters
            capitalize(value){
                if (!value) return ''; // When the passed in value is null, an empty string is returned
                value = value.toString(); // Convert the passed in value to String type
                return value.charAt(0).toUpperCase() + value.slice(1) // Convert the first letter of the string to uppercase and splice the following string
            }

        }
    })
</script>

</body>
</html>

The browser executes as follows:

2. How to define the global filter

    // 3. Define a global filter to override the local filter
    Vue.filter('capitalize', function (value) {
        if (!value) return ''; // When the passed in value is null, an empty string is returned
        value = value.toString(); // Convert the passed in value to String type
        // Convert the first and second letters of the string to uppercase and splice the following string
        return value.charAt(0).toUpperCase() + value.charAt(1).toUpperCase() +  value.slice(2) + 'Global filter'
    })

Because when the global filter and local filter have the same name, the local filter will be used. Therefore, first annotate the above local filter to see the effect, as follows:

3. Confirm that when the global filter and local filter have the same name, the local filter will be used

The browser displays as follows:

Filters can be connected in series:

{{ message | filterA | filterB }}

In this example, filterA is 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 to call the filter function filterB, which is also defined to receive a single parameter, and pass the result of filterA to filterB.

Next, write a local filter to replace the a character with b using replace (regular string).

// Replace the filter with the characters a and b
replace_str(value){
  return value.replace(/a/g, 'b') // Regular content is in the slash, and g represents global replacement
}

Next, use the series filter to continue to replace the minimum filtered data, as follows:

The browser displays as follows:

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

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

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

In the replacement character filter above, only a can be replaced with the letter b. the incoming parameter is set below to replace it according to the parameter.

// Replace the filter of character a according to the parameter
replace_str(value, arg1, arg2){
  return value.replace(/a/g, arg1 + arg2) // Regular content is in the slash, and g represents global replacement
}

The following parameters are passed in where the filter is used:

<!-- 2.set up p Note rendering msg Data, that is, when the input box is filled with information, then p The labels are rendered synchronously   -->
<p>{{ msg | capitalize | replace_str('c','d') }}</p>

The browser displays as follows:

As you can see from the browser, a character a is replaced by cd.

Reference

[1]

Vue.filter( id, [definition] ): https://cn.vuejs.org/v2/api/#Vue-filter