vue--过滤器

过滤器

过滤器对将要显示的文本,先进行特定格式化处理,然后再进行显示。

注意:过滤器并没有改变原来的数据,只是产生新的对应的数据。

过滤器有全局过滤器和局部过滤器两种。

全局过滤器(没有s)
Vue.filter(过滤器名称,function(value,value2...){
    // 数据处理逻辑 
})
局部过滤器

在Vue实例中使用filters选项,当前实例范围内可用

new Vue({
filters(过滤器名称,
function(value,value2...){ // 数据处理逻辑 }
)
)
}

过滤器可以用在两个地方,双花括号{{ }}和v-bind表达式


<div>{{数据属性名称 | 过滤器名称}}div>
<div>{{数据属性名称 | 过滤器名称(参数值)}}div>

<div v-bind:id="数据属性名称 | 过滤器名称">div> <div v-bind:id="数据属性名称 | 过滤器名称(参数值)">div>

目的:实现过滤敏感字符,如文本中有tmd,sb的都进行过滤掉

全局过滤器

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Documenttitle>
    <script src="./node_modules/vue/dist/vue.js">script>
head>
<body>
    <div id="app">
            <h3>测试过滤器单个参数h3>
            
            <p>{{content | contentFilter}}p> 
            <input type="text" :value="content | contentFilter">
    div>
    
    <script>
       /*全局过滤器*/
         Vue.filter('contentFilter', function (value) {
            if(!value) {
                return ''
            }
            // toString()转为字符串,toUpperCase()转为大写
            return value.toString().toUpperCase().replace('TMD', '***').replace('SB', '***')
        }) 

        new Vue({
            el: "#app",
            data: {
                content: "你TMD真SB"
            }
        })
    script>
    
body>
html>

局部过滤器

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Documenttitle>
    <script src="./node_modules/vue/dist/vue.js">script>
head>
<body>
    <div id="app">
            <h3>测试过滤器单个参数h3>
            
            <p>{{content | contentFilter}}p> 
            <input type="text" :value="content | contentFilter">
            <input type="text" :value="javaScore | add(vueScore, pythonScore)">
    div>
    
    <script>
      

        new Vue({
            el: "#app",
            data: {
                content: "你TMD真SB",
                javaScore: 90,
                vueScore: 99,
                pythonScore: 89
            },
            filters: { //定义局部 过滤器
                contentFilter (value) { // contentFilter 过滤名, value
                    if(!value) {
                        return ''
                    }
                    return value.toString().toUpperCase().replace('TMD', '***').replace('SB', '***')
                },

                add (num1, num2, num3) {// add 过滤名, num1 其实就是引用时 | 左边的那个参数
                    return num1 + num2 + num3
                }
            }
        })
    script>
    
body>
html>

你可能感兴趣的:(vue--过滤器)