SoFunction
Updated on 2025-04-04

How to use vue filter filter

Overview

Before vue2.0, there were built-in filters, and there were no built-in filters in 2.0, but we can customize the filters.

Regarding vue filters, the official documentation explains this:

Allows you to customize filters that can be used for some common text formatting. Filters can be used in two places: double brace interpolation and v-bind expressions (the latter is supported starting with 2.1.0+). Filters should be added at the end of a JavaScript expression, indicated by the "pipe" symbol.

That is, a filter is a function used to format data. The filter will not modify the original data. Its function is to filter the data, which is to process the data and return the processed data, such as making some modifications to the data format, state conversion, etc.

There are two types of filters

  • Filters within components (effective within components)
  • Global filters (shared by all components)

Define filters

The first parameter is the filter name

The second parameter is the function function of the filter (if you don’t define vue, you won’t know what this string is and what it does).

Functional functions of filters

  • Declare function(data,argv1,argv2...){}
  • The first parameter is the data to be filtered in, that is, the content on the left side of the pipe character when called.
  • The second parameter starts and goes on and afterwards are the parameters passed in when the filter is called.

Use of filters

Register first, then use

In component filters:{ filter name: fn } In fn, return the final data

Global ('filter name',fn) Return the final data in fn

Use {{ Data | Filter Name }}

// When using filters, you need to add a pipe symbol ( | ) as a separation. Pipe character | on the right is the filter name, that is, the function function of the text​
<!-- In double braces -->
{{ message | Filter name }}
​
<!-- exist `v-bind` middle -->
<div v-bind:></div>

Custom global filters

('Filter Name', function(val) { // val indicates the data to be processed    // Filter business logic, need to have a return value})
​
<div>{{ msg | Filter name }}</div>
<div v-bind="msg | filter name"></div>

Local filter

data () {
    return {
        msg: 'hello world'
    }
},
//Define private local filters.  Only available in the current vue objectfilters: {
    dataFormat: (msg, a) => { // msg represents the data to be filtered, a represents the parameters passed in        return msg + a;
    }
}
​
<p>{{ msg | dataFormat('!')}}</p> // result: hello world!

Things to note

1. When registering globally, filters have no s, while the component filters have filters, which have s. Although there is no s when writing, there is no error, but the filter has no effect.

2. When the names of the global filter and local filter are repeated, they will be called based on the principle of proximity, that is, the local filter is called priority over the global filter.

3. An expression can use multiple filters, and its execution order is from left to right. The result of the previous filter is used as the processed data of the latter filter, so pay attention to the order of use.

Children's shoes familiar with vue will know that filters can sometimes achieve the purpose of processing data like methods, computed, and watch, but they cannot replace them because they cannot change the original value. If the internal complexity of a filter, you can consider writing it as a computed property, because the computed property itself has a cache and is highly reusable, and the filter is generally used to do some simple operations.

In actual development, global filters are more widely used than local filters. To put it bluntly, why do we use filters? In fact, it is the same as using functions. Some methods are encapsulated for other components to use, so that they are more convenient and faster to call.

As we all know, global filters are defined in , but if the project is too large and there are multiple filters, then there is a bunch of code. In order to make the project modular, it is best to have a special directory to store these filters in a unified manner, and then extract the processing functions and place them in a .js file. The following is shown by example code.

Example 1 (local filter)

Format the time or date, complete the specified digits, and make up 0 if the number is less than single digits

// filter/fileexport default {
    dateFormat: value => {
        const dt = new Date(value * 1000)
    
        const y = ()
        const m = (() + 1 + '').padStart(2, '0') // .padStart (Specify the number of digits, "Symbol or Value to be completed")        const d = (() + '').padStart(2, '0')
        
        const hh = (() + '').padStart(2, '0')
        const mm = (() + '').padStart(2, '0')
        const ss = (() + '').padStart(2, '0')
        
        return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
    }
}
​
// Use local filters in .vue files<script>
    import filters from '../filter'
​
    export default {
        ... ... 
        filters: { ...filters },
        data() {
            return {}
        }
    }
</script>
​
<div> date:{{ date | dateFormat }} </div>

Example 2 (Global Filter)

Echo of the general dictionary item: For example, gender, male and female or universal selection, the data transmitted to us by the backend is 0 or 1, and we need to display male and female or whether on the page

// constants/ file​
export const GENDER_MENU = [
    { code: 0, label: 'male'},
    { code: 1, label: 'female'}
];
​
export const COMMON_MENU = [
    { code: 0, label: 'no'},
    { code: 1, label: 'yes'}
];
​
export default {
    GENDER_MENU, COMMON_MENU
}

filter / file

// filter/ file​
import Dict from '../constants/dictionary'
​
export const genderMenu = {
    func: value => {
        const target = Dict.GENDER_MENU.filter(item => {
            return  = value;
        })
        return  ? target[0].label : value;
    }
}
​
export const commonMenu = {
    func: value => {
        const target = Dict.COMMON_MENU.filter(item => {
            return  = value;
        })
        return  ? target[0].label : value;
    }
}

filter / file

// filter/ file​
import * as filters from './dict' // Import filtering functions​
const Install = Vue => {
    // The imported filters is an object. Use the() method to get an array composed of keys, traverse the data, and let the key be the name of the global filter. The following is the processing function corresponding to the key, so that the global filter can be used in any component.    (filters).forEach(key => {
        (key, filters[key].func)
    })
    /*
    for(const _filter in filters) {
        (`${_filter}`, filters[_filter].func)
    } */
}
​
export default Install

document

//  document​
... ...
import filters from  './../filter/index'
(filters)
... ...

Use global filters in .vue files

// Use global filters in .vue files​
<p>gender:{{ gender | genderMenu }}</p>  

The above is the detailed content of how to use vue filter filter. For more information about vue filter filter, please follow my other related articles!