在Vue2中,可以使用过滤器(filters)来实现对数据的格式化处理

196 阅读1分钟

在Vue2中,可以使用过滤器(filters)来实现对数据的格式化处理。下面是一个将数字转换为千位分隔符形式的过滤器的示例:

<template> 
    <div>{{ money | toThousand }}</div> 
</template> 

<script> 
    export default { 
        data() { 
            return { 
                money: 1234567.89 
            } 
        }, 
        filters: { 
            toThousand(value) { 
                if (!value) return '' 
                let result = value.toString().replace(/\d+/, function(n) { 
                // 先提取整数部分 
                return n.replace(/(\d)(?=(\d{3})+$)/g, function($1) { 
                    return $1 + ',' 
                    }) 
                }) 
                if (result.indexOf('.') !== -1) {
                    // 处理小数部分 
                    let decimal = result.split('.')[1] 
                    result = result.split('.')[0] + '.' + decimal.padEnd(2, '0') 
                } else { 
                    result += '.00' 
                } 
                return result 
                }
             } 
   }
</script>