current position:Home>One who writes an article must master Vue immediately. (6) filters

One who writes an article must master Vue immediately. (6) filters

2022-01-29 15:24:01 Silver rain starry sky

The data we render to the page is usually from the database , The data stored in the database is often difficult for us to predict , In order to avoid data formats beyond our expectations , We need to filter .

  • tip:2020 year 9 month ,vue3 Come out . Added a lot of new features , But some of the features have also been deleted . Like deleting vue2 Filter in filter function . meanwhile , The official advice : Replace the filter with a method call or calculated property .

filters filter

Filter use

filter seeing the name of a thing one thinks of its function , Filter out unwanted data , Not without data , It's dealing with , Usually cut .

The basic format : {{ Variable | Functions that handle variables , This function comes from filters object }}

    <div id="app" v-cloak>
        <div>{{num|showNum}}</div>
    </div>
 Copy code 
......
            data:{
                num:123.231
            },
            filters:{
                showNum(num){
                    return num.toFixed(1)
                }
            }
......
 Copy code 

image.png

——v- Use filters in instructions

We are apart from Interpolation expression Use a filter in the , We can still do that v- Instructions Use a filter in the .

<input type="text" :value="num|showNum" id="">
{{num}}
 Copy code 

image.png

Note that if in use v- Use filters on directives or attributes .

Multivalued filter

adopt | The previous variable is used as the parameter of the filter , I can also add more parameters . Through the following format :

<div>{{string|showString(' Start with a capital :')}}</div>
 Copy code 

In the case of multiple values , The default acceptance parameter is | Variables before , And by () The passed in argument is assigned to the subsequent parameter , And you can pass in multiple parameters for function design .

......
            filters:{
......
                showString(str1,str2){
                    //str1 Namely string
                    return str2 + str1.replace(/^[^]/,($)=>$.toUpperCase())
                }
            }
......
 Copy code 

image.png

Nested filter

If v-for equally , We use filter You can also nest , Because I can put the original Interpolation expression As a whole variable .

        <div>{{speed|moreSpeed|moreSpeed}}</div>
        {{speed}}
 Copy code 
......
moreSpeed(speed){
    return speed*2
}
......
 Copy code 

image.png


As said at the beginning, our filter itself is no longer vue3 Reserved , So I suggest you just study for the purpose of learning , Reduce use in projects , For the future vue2 turn vue3 Smooth and preventive Injection .

copyright notice
author[Silver rain starry sky],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/01/202201291523590126.html

Random recommended