Vue filters, filter 过滤器

过滤器 

  • 作用:文本数据格式化
  • 两种过滤器:1 全局过滤器 2 局部过滤器

全局过滤器 filter

说明:通过全局方式创建的过滤器,在任何一个vue实例中都可以使用

实例:时间戳对象转换

//组件中调用 过滤器dateFormatYMD 

<div>{{ date | dateFormatYMD }}</div>


<script>

//mian.js中  return 格式为2019-03-02
  Vue.filter('dateFormatYMD',function (value) {
        if (!value) {
            return '- -';
        } else {
            Date.prototype.Format = function (fmt) { //author: wayne
                var o = {
                    "M+": this.getMonth() + 1, //月份
                    "d+": this.getDate(), //日
                    "H+": this.getHours(), //小时
                    "m+": this.getMinutes(), //分
                    "s+": this.getSeconds(), //秒
                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                    "S": this.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" +
                        o[k]).substr(("" + o[k]).length)));
                return fmt;
            }
            var msesInt = value; // 毫秒字符串转换成数值
            var dt = new Date(msesInt); // 初始化Date对象
            var ndt = dt.Format("yyyy-MM-dd");
            return ndt;
        }
    }
)
</script>

 局部过滤器 

  • 说明:局部过滤器是在某一个vue实例的内容创建的,只在当前实例中起作用
{
  data: {},
  // 通过 filters 属性创建局部过滤器
  filters: {
    filterName: function(value) {}
  }
}
  • 本地过滤器被注册到一个Vue组件中。下面这个示例展示了本地过滤器是如何创建的。
  • 这个过滤器的功能是将字母变成大写:
    <div id="app">
        <h1>{{ name | Upper}}</h1>
    </div>
    <script src="./vue.js"></script>
    <script>
        var vm = new Vue({
            el: '#app',
            data () {
                return {
                    name : 'vue'
                }
            },
            //声明一个本地的过滤器
            filters: {
                Upper: function(value) {
                        return value.toUpperCase()
                    }
            }
        })
    </script>

 

过滤器可以串联:

{{ message | filterA | filterB }}

在这个例子中,filterA被定义为接收单个参数的过滤器函数,表达式message的值将作为参数传入到函数中。然后继续调用同样被定义为接收单个参数的过滤器函数filterB,将filterA的结果传递到filterB中。

过滤器可以接收参数:

滤器是 JavaScript 函数,因此可以接收参数:

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

这里,filterA被定义为接收三个参数的过滤器函数。其中message的值作为第一个参数,普通字符串'arg1'作为第二个参数,表达式arg2的值作为第三个参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值