Vue自定义过滤器

来源:互联网 发布:linux 查看网卡流量 编辑:程序博客网 时间:2024/05/24 04:10

虽然VueJs给我们提供了很多强有力的过滤器,但有时候还是不够。值得庆幸的,Vue给我们提供了一个干净简洁的方式来定义我们自己的过滤器,之后我们就可以利用管道 “ | ” 来完成过滤。

定义一个全局的自定义过滤器,需要使用Vue.filter()构造器。这个构造器需要两个参数。

Vue.filter() Constructor Parameters:

1.filterId: 过滤器ID,用来做为你的过滤器的唯一标识;

2.filter function: 过滤器函数,用一个function来接收一个参数,之后再将接收到的参数格式化为想要的数据结果。

上面的例子中,我们要实现商品价格打5折该怎么做呢?其实就是实现的一个自定义的过滤器,表示将商品的价格打了5折;而要实现它,需要完成的是:

a、使用Vue.filter()构造器创建一个过滤器叫做discount

b、输入商品的原价,能够返回其打五折之后的折扣价

Vue.filter('discount', function(value) {    return value * .5;});var product = new Vue({    el: '.product',    data: {        products: [            {name: '苹果',price: 25,category: "水果"},             {name: '香蕉',price: 15,category: "水果"},             {name: '雪梨',price: 65,category: "水果"},             {name: '宝马',price: 2500,category: "汽车"},            {name: '奔驰',price: 10025,category: "汽车"},             {name: '柑橘',price: 15,category: "水果"},             {name: '奥迪',price: 25,category: "汽车"}        ]    },})
现在就可以像使用Vue自带的过滤器一样使用自定义过滤器了

<ul class="product">    <li v-for="product in products|filterBy '水果' in 'category' |orderBy 'price' 0">        {{product.name}}-{{product.price|discount | currency}}    </li></ul>
上面代码实现的商品打5折,而如果要实现价格打任意折扣呢?应该在discount过滤器里增加一个折扣数值参数,改造一下我们的过滤器

Vue.filter('discount', function(value, discount) {    return value * (discount / 100);});
然后重新调用我们的过滤器

<ul class="product">    <li v-for="product in products|filterBy '水果' in 'category' |orderBy 'price' 0">        {{product.name}}-{{product.price|discount 25 | currency}}    </li></ul>
我们也可以在我们Vue实例里构造我们的过滤器,这样构造的好处是,这样就不会影响到其他不需要用到这个过滤器的Vue实例。

/*定义在全局 Vue.filter('discount', function(value,discount) {    return value  * ( discount / 100 ) ;});*/var product = new Vue({    el: '.product',    data: {        products: [            {name: '苹果',price: 25,category: "水果"},             {name: '香蕉',price: 15,category: "水果"},             {name: '雪梨',price: 65,category: "水果"},             {name: '宝马',price: 2500,category: "汽车"},            {name: '奔驰',price: 10025,category: "汽车"},             {name: '柑橘',price: 15,category: "水果"},             {name: '奥迪',price: 25,category: "汽车"}        ]    },    //自定义在实例    filters: {        discount: function(value, discount) {            return value * (discount / 100);        }    }})

0 0
原创粉丝点击