vue filter函数的用法_Vue串联过滤器的使用场景

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 19:15   2305   0

71de4368c94c10cf2886d06c8d3866b6.png

平时开发中,需要用到过滤器的地方有很多,比如单位转换、数字打点、文本格式化等,比如:

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.$http://options.filters.XXX
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP