• Vue中如何使用filter 过滤器


    一、入门

    filter 介绍

    1、 有时需要 例如 一些数据格式($ 20.00)、最大值(一些逻辑处理后,返回想要的格式或者数据);可以使用 filter 。
    2、VUE 中的过滤器不能替代Vue中的methods、computed或者watch
    3、过滤器不改变真正的data,而只是改变渲染的结果,并返回过滤后的版本。
    4、过滤器好处,尽可能保持API响应的干净、在前端处理数据格式。
    5、在Vue 2.0 已经无内置的过滤器了,可自定义过滤器。

    filter 参数

    1、可使用到两个地方

    <!-- 花括号中使用 -->
    <div>{{money|moneyFilter(2,'元')}}</div>
    
    <!-- v-bind 中使用 -->
    <div :id="id | capitalize"></div>
    

    2、filter 管道 传参

    tempure : 过滤器中传递的值 或者表达式 (obj、arr 等);
    a:参数 1 ;
    b:参数 2 
    
    <div :id=" tempure | filterFn(a,b)">我是过滤器</div>
    <div>{{tempure | filterFn1(a,b) | filterFn2(a,b)}}</div>
    

    二、全局使用

    在main.js 中 定义

    1、moneyFilter:过滤器名称
    2、函数中的参数解析:
    value:通过管道传来的数据
    num:调用过滤器时在圆括号中第一个参数
    type:调用过滤器时在圆括号中第二个参数

    Vue.filter("moneyFilter", function(value, num, type) {
      //value是使用过滤器是的表达式或者值,num和tyep中的参数
      return "¥" + value.toFixed(num) + type;
    });
    

    在 需要的地方引用

    {{20 | moneyFilter(2,'元')}}            // 20:00 元
    

    三、局部(组件内)使用

    filters:{
        moneyFilter: function(value, num, type) {
            return "¥" + value.toFixed(num) + type;
        },
    },
    

    在 需要的地方引用

    {{20 | moneyFilter(2,'元')}}            // 20:00 元
    

    文件定义全局过滤器

    自定义函数(filterfun.js)中

    //金额格式过滤器
    let moneyFilter = (value, num, type) => {
     return "¥" + value.toFixed(num) + type;
    };
    
    ecport default {
      moneyFilter, 
    }
    

    在 main.js 中引入

    import * as filterfun from "./filters";
    3、注册自定义过滤器

    Object.keys(filterfun ).forEach(key => {
      Vue.filter(key, filterfun[key]);
    });
    
  • 相关阅读:
    Design Patterns
    Interview
    ListView Optimization
    android onclick onLongClick ontouch dispatchTouchEvent onInterceptTouchEvent
    java hashcode equals
    Android res/raw vs assets
    HttpClient -- 血的教训
    How Android Draws Views
    元数据 metadata
    Git-2
  • 原文地址:https://www.cnblogs.com/cjh1996/p/12690524.html
Copyright © 2020-2023  润新知