过滤器
- 作用:文本数据格式化
- 两种过滤器: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
的值作为第三个参数。