局部过滤器

在当前组件内部使用,给某些数据 "添油加醋",局部过滤器写在组件的选项中,使用filters定义

 1 let App = {
 2             data(){
 3                 return {
 4                     msg:"hello world",
 5                     time:new Date()
 6                 }
 7             },
 8             template:`
 9                 //使用局部过滤器 ,前边是值,后边是过滤器名字
10                <div>我是一个APP  {{ msg | myReverse }}
11                 <h2>{{ time | myTime('YYYY-MM-DD')}}</h2>
12 
13                </div>
14             `,
15             //定义局部过滤器
16             filters:{
17                 //过滤器名字:function(参数:这个参数是要处理的数据){return }
18                 myReverse:function (val) {
19                     console.log(val);
20                     return val.split('').reverse().join('')
21                 },
22                 //年-月- 日  年- 月
23                 myTime:function(val,formatStr){
24                     return moment(val).format(formatStr);
25                 }
26             }
27         }
View Code

全局过滤器

只要过滤器一创建,可以在任何组件中使用,使用 filter 定义

 1 //定义全局过滤器 ('过滤器名字',function(参数
 2 Vue.filter('myTime',function (val,formatStr) {
 3             return moment(val).format(formatStr)
 4         })
 5         let App = {
 6             data(){
 7                 return {
 8                     msg:"hello world",
 9                     time:new Date()
10                 }
11             },
12             template:`
13                 //过滤器的使用
14                <div>我是一个APP  {{ msg | myReverse }}
15             //此处可以传参,由上边的formatStr接收,灵活处理数据
16                 <h2>{{ time | myTime('YYYY-MM-DD')}}</h2>
17 
18                </div>
19             `,
20         }
View Code