欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Vue串聯(lián)過(guò)濾器的使用場(chǎng)景

 更新時(shí)間:2020年04月30日 10:51:54   作者:尹成諾  
這篇文章主要介紹了詳解Vue串聯(lián)過(guò)濾器的使用場(chǎng)景,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

平時(shí)開發(fā)中,需要用到過(guò)濾器的地方有很多,比如單位轉(zhuǎn)換、數(shù)字打點(diǎn)、文本格式化等,比如:

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

實(shí)現(xiàn)效果:

30000 => 30,000

當(dāng)然這只是常規(guī)用法,沒(méi)什么好說(shuō)的。下面來(lái)說(shuō)一個(gè)我在開發(fā)中遇到的一個(gè)需要用到串聯(lián)過(guò)濾器的使用場(chǎng)景。

假設(shè)需要獲取一個(gè)訂單列表,其中的每一項(xiàng)的 status 字段用來(lái)表示訂單狀態(tài):        

 {
      id: '',
      order_num: '123456789',
      goodList: [ ... ],
      address: { ... },
      status: 1 // 1 待付款 2 待發(fā)貨 3 待收貨
     }

那我們拿到這個(gè)數(shù)據(jù)在,v-for 的時(shí)候,肯定會(huì)這樣做:

 <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 '待發(fā)貨';
        case '1':
          return '待收貨';
        default:
          return '';
      }
    }
  }
  // ...
 }
</script>
<style scoped type="scss">
  // ...
  .order_status {
    font-size: 14px;
  }
  // ...
</style>

這樣,表示狀態(tài)的 1, 2, 3 就變成了 待付款,待發(fā)貨,待收貨。這沒(méi)有什么問(wèn)題。但是,需求來(lái)了,當(dāng)訂單未付款時(shí),表示狀態(tài)的文字應(yīng)該為紅色。就是當(dāng)狀態(tài)為 待付款 時(shí),文字要為紅色!這個(gè)問(wèn)題曾經(jīng)困擾了有一段時(shí)間,用了各種辦法,雖然也是實(shí)現(xiàn)了需求,但終歸不太優(yōu)雅。直到最近在翻看 vue 文檔,才想起來(lái)有串聯(lián)過(guò)濾器的用法,可以完美解決這個(gè)需求,上碼:

<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 '待發(fā)貨';
        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>

就這么簡(jiǎn)單。

關(guān)于過(guò)濾器,這里還有幾點(diǎn)要注意的:

  • 過(guò)濾器必須是個(gè)純函數(shù)
  • 過(guò)濾器中拿不到 vue 實(shí)例,這是 vue 故意這么做的
  • 在全局注冊(cè)過(guò)濾器是用 Vue.filter(),局部則是 filters: {}
  • 在方法中調(diào)用過(guò)濾器方法為: this.$options.filters.XXX

到此這篇關(guān)于詳解Vue串聯(lián)過(guò)濾器的使用場(chǎng)景的文章就介紹到這了,更多相關(guān)Vue串聯(lián)過(guò)濾器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評(píng)論