iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 24
1
自我挑戰組

vue.js 30天學習軌跡系列 第 24

Day24 vue.js -使用 filters 來過濾

filters在兩個地方可用:{{ }}v-bind表達式(2.1.0+支持後者)。
filters應附加在JavaScript表達式的末尾,並以 | 符號表示

局部註冊

局部註冊直接在組件內寫filters即可,但是只能在當前組件內使用

<div id="app">
  <table class="table">
    <tbody>
      <tr is="component" v-for="(item, key) in timeData" :item="item" :key="key"></tr>
    </tbody>
  </table>
</div>

<script type="text/x-template" id="filter-component">
  <tr>
    <td>{{ item.name }}</td>
    <td>{{ item.price | currency | dollarSign}}</td>
  </tr>
</script>
var child = {
  props: ['item'],
  template: '#filter-component',
  filters:{
    dollarSign(val){
       return `$ ${val}`
    },
    currency(n){
      return n.toFixed(2).replace(/./g, function(c, i, a) {
      return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
      });
    },
  }
}
var app = new Vue({
  el: '#app',
  data: {
    timeData: [
       {
        name: '薯條',
        price: 20,
      },
      {
        name: '甜不辣',
        price: 25,
      },
      {
        name: '黃金雞排',
        price: 55000,
      },
    ]
  },
  components: {
    "component": child
  },
});

全局註冊

直接在vue上使用filter方法註冊過濾器,這種全局註冊的過濾器在任何一個組件內都可以使用。
Vue.filter('functionName', function(n) { });

Vue.filter('dollarSign', function(n) {
  return `$ ${n}`
});
Vue.filter('currency', function(n) {
  return n.toFixed(2).replace(/./g, function(c, i, a) {
    return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
  });
});

傳遞順序

currency傳到 item.price裡面做千分號,再傳入dollarSign加上$字號,
若 順序相反 會因為無法將 $20000 轉為 千分號而發生錯誤喔!!

ps: 對不起...我只會用小畫家 畫的有點醜/images/emoticon/emoticon06.gif


上一篇
Day23 vue.js - Vue.extend構造器
下一篇
Day25 vue.js - 使用$set寫入資料
系列文
vue.js 30天學習軌跡30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言