概述
平时开发中,需要用到过滤器的地方有很多,比如单位转换、数字打点、文本格式化等,比如:
Vue.filter('toThousandFilter', function (value) { if (!value) return '' value = value.toString() return .replace(str.indexOf('.') > -1 ? /(d)(?=(d{3})+.)/g : /(d)(?=(?:d{3})+$)/g, '$1,') })
实现效果:
30000 => 30,000
当然这只是常规用法,没什么好说的。下面来说一个我在开发中遇到的一个需要用到串联过滤器的使用场景。
假设需要获取一个订单列表,其中的每一项的 status 字段用来表示订单状态:
{ id: '', order_num: '123456789', goodList: [ ... ], address: { ... }, status: 1 // 1 待付款 2 待发货 3 待收货 }
那我们拿到这个数据在,v-for 的时候,肯定会这样做:
<template> <!-- ... --> <span class="order_status">{{ orderItem.status | getOrderStatus }}</span> <!-- ... --> </template> <script> export default { // ... filters: { getOrderStatus(status) { switch (status.toString()) { case '1': return '待付款'; case '1': return '待发货'; case '1': return '待收货'; default: return ''; } } } // ... } </script> <style scoped type="scss"> // ... .order_status { font-size: 14px; } // ... </style>
这样,表示状态的 1, 2, 3 就变成了 待付款,待发货,待收货。这没有什么问题。但是,需求来了,当订单未付款时,表示状态的文字应该为红色。就是当状态为 待付款 时,文字要为红色!这个问题曾经困扰了有一段时间,用了各种办法,虽然也是实现了需求,但终归不太优雅。直到最近在翻看 vue 文档,才想起来有串联过滤器的用法,可以完美解决这个需求,上码:
<template> <!-- ... --> <span class="order_status" :class="orderItem.status | getOrderStatus | getOrderStatusClass">{{ orderItem.status | getOrderStatus }}</span> <!-- ... --> </template> <script> export default { // ... filters: { getOrderStatus(status) { switch (status.toString()) { case '1': return '待付款'; case '1': return '待发货'; case '1': return '待收货'; default: return ''; } }, getOrderStatusClass(status) { if (status === '待付款') { return 'not-pay' } return '' } } // ... } </script> <style scoped type="scss"> // ... .order_status { font-size: 14px; &.not-pay { color: red; } } // ... </style>
就这么简单。
关于过滤器,这里还有几点要注意的:
- 过滤器必须是个纯函数
- 过滤器中拿不到 vue 实例,这是 vue 故意这么做的
- 在全局注册过滤器是用 Vue.filter(),局部则是 filters: {}
- 在方法中调用过滤器方法为: this.$options.filters.XXX
到此这篇关于详解Vue串联过滤器的使用场景的文章就介绍到这了,更多相关Vue串联过滤器内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!
最后
以上就是从容睫毛膏为你收集整理的详解Vue串联过滤器的使用场景的全部内容,希望文章能够帮你解决详解Vue串联过滤器的使用场景所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复