Vue.js 自定义过滤器,为了对数据更方便的处理显示就需要用到过滤器
优点
1.过滤器可以串联
2.可以定义全局过滤器,复用性高,方便
3.没有缓存,被调用时才计算
1.在main.js中引入和注册全局过滤器
// 过滤器
import
* as filters from
'./filters'
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key])
})
你可以在一个组件的选项中定义局部的过滤器,但只能在局部引用:
filters: { capitalize: function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) } }
格式化成类似 2019-07-18 11:54:16
格式化成类似 2019-07-18
/** * 格式化日期 * 格式化成类似 2019-07-18 11:54:16 */ export function formatDatetime (datetime) { if (datetime != null) { const dateMat = new Date(datetime); const year = dateMat.getFullYear(); const month = (dateMat.getMonth() + 1 < 10 ? "0" + (dateMat.getMonth() + 1) : dateMat.getMonth() + 1); const day = dateMat.getDate() < 10 ? "0" + dateMat.getDate() : dateMat.getDate(); const hh = dateMat.getHours() < 10 ? "0" + dateMat.getHours() : dateMat.getHours(); const mm = dateMat.getMinutes() < 10 ? "0" + dateMat.getMinutes() : dateMat.getMinutes(); const ss = dateMat.getSeconds() < 10 ? "0" + dateMat.getSeconds() : dateMat.getSeconds(); var timeFormat = year + '-' + month + '-' + day + ' ' + hh + ':' + mm + ':' + ss; return timeFormat; } } /** * 格式化日期 * 格式化成类似 2019-07-18 */ export function formatDate (date) { if (date != null) { const dateMat = new Date(date); const year = dateMat.getFullYear(); const month = (dateMat.getMonth() + 1 < 10 ? "0" + (dateMat.getMonth() + 1) : dateMat.getMonth() + 1); const day = dateMat.getDate() < 10 ? "0" + dateMat.getDate() : dateMat.getDate(); const timeFormat = year + '-' + month + '-' + day; return timeFormat; } }
千分号
/** * 10000 => "10,000" * 千分号 * @param {number} num */ export function toThousandFilter(num) { return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ',')) } /*千分号兼取两位小数*/ export function toThousandFloat(num) { if(num != '' && num != null && typeof(num) != 'undefined') { return parseFloat(num).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') }else { return 0; } }
千进制10000 => 10k
/** * like 10000 => 10k * @param {number} num */ export function numberFormatter(num, digits) { const si = [ { value: 1E18, symbol: 'E' }, { value: 1E15, symbol: 'P' }, { value: 1E12, symbol: 'T' }, { value: 1E9, symbol: 'G' }, { value: 1E6, symbol: 'M' }, { value: 1E3, symbol: 'k' } ] for (let i = 0; i < si.length; i++) { if (num >= si[i].value) { return (num / si[i].value + 0.1).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol } } return num.toString() }
使用
使用方法有两种
<!-- 在双花括号中 --> {{ message | capitalize }} <!-- 在 `v-bind` 中 --> <div v-bind:id="rawId | formatId"></div>