vue---filters过滤器的使用

一、什么是过滤器?

  过滤器是对即将显示的数据做进一步的筛选处理,然后进行显示,值得注意的是过滤器并没有改变原来的数据,只是在原数据的基础上产生新的数据。

官方文档

apihttps://cn.vuejs.org/v2/guide/filters.html

过滤的使用场景很广泛,如单位转换、数字打点、文本格式化、日期格式化、大小写转化等。

Vue串联过滤器的使用场景

https://zhuanlan.zhihu.com/p/137136945

关于过滤器,这里还有几点要注意的:

  • 过滤器必须是个纯函数
  • 过滤器中拿不到 vue 实例,这是 vue 故意这么做的
  • 在全局注册过滤器是用 Vue.filter(),局部则是 filters: {}
  • 在方法中调用过滤器方法为: this.$

1.数字打点

全局定义

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,')
})

使用

<div>{{ 30000 | toThousandFilter}}</div>

效果

30000 => 30,000

2.串联过滤器

假设需要获取一个订单列表,其中的每一项的 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 '2':
                    return '待发货';
                case '3':
                    return '待收货';
                default:
                    return '';
            }
        }
    }
    // ...
  }
</script>

这样,表示状态的 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 '2': return '待发货'; case '3': 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>
原文地址:https://www.cnblogs.com/miangao/p/14473582.html