一、全局过滤器
1 2 3 4 5
|
Vue.filter('filterName', function (value) { })
|
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| Vue.filter('date', function (input, format = 'yyyy-MM-dd hh:mm:ss'){ var o = { "M+": input.getMonth() + 1, //月份 "d+": input.getDate(), //日 "h+": input.getHours(), //小时 "m+": input.getMinutes(), //分 "s+": input.getSeconds(), //秒 "q+": Math.floor((input.getMonth() + 3) / 3), //季度 "S": input.getMilliseconds() //毫秒 };
if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (input.getFullYear() + "").substr(4 - RegExp.$1.length)); // 不够2位的前面补0 for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return format; })
|
使用
1
| <h1>{{item.time | date('yyyy-MM-dd hh:mm:ss')}}h1>
|
一个项目中,可能要用到很多过滤器来处理数据,多个组件公用的,可以注册全局过滤器。单个组件使用的,就挂载到实例filters中。项目做的多了以后,可以整理一套常用的filters,不用反复的写。比如:时间等各种操作,数据格式转化,单位换算,部分数据的md5加密等…
创建一个filters专门放各种过滤器

filter.js

main.js

页面上直接用 ’|过滤器名‘ 即可

或者直接在main.js中直接自定义全局过滤器

二、局部过滤器
在某一个vue实例的内创建的,只在当前实例中起作用
1 2 3 4 5 6 7 8 9 10
| new Vue({ data:{ }, filters: { filterName: function(value, format) {} } })
|