当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解Vue串联过滤器的使用场景

详解Vue串联过滤器的使用场景

2020年05月10日  | 移动技术网IT编程  | 我要评论

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

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串联过滤器内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网! 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网