关于过滤器
- 注册过滤器:Vue.filter(name, callback) 或 new Vue({filters: {...}})
- 使用过滤器:{{xxx | filter_name}} 或 v-bind:www="xxx | filter_name"
- 过滤器可以接受除过滤对象以外的其他参数,也可以多个过滤器串联
- 过滤器不会改变原本的数据,而是产生新的数据
示例
以将js时间戳转化为正常时间格式为例,使用dayjs库
<h1>The Time Now is {{time | timeFormatter}}</h1>
<h1>The Time Now is {{time | timeFormatter('YYYY_MM_DD')}}</h1>
<h1 :x="msg | msgFormatter">Using filter inside the tags</h1>
在vue实例中,配置过滤器属性 -- 和data/method属性同级
filters: {
timeFormatter(val, str='YYYY-MM-DD HH:mm:ss'){
return dayjs(val).format(str)
}
}
或者配置全局过滤器 -- 和vue实例同级
Vue.filter('mySlice', function(value){
return value.slice(0, 4)
})