如何在 Vue 组件中格式化货币?

新手上路,请多包涵

我的 Vue 组件是这样的:

 <template>
    <div>
        <div class="panel-group"v-for="item in list">
            <div class="col-md-8">
                <small>
                   Total: <b>{{ item.total }}</b>
                </small>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        ...
        computed: {
            list: function() {
                return this.$store.state.transaction.list
            },
            ...
        }
    }
</script>

{{ item.total }} 的结果是

26000000

但我希望它的格式是这样的:

26.000.000,00

在 jquery 或 javascript 中,我可以做到

但是,如何在 vue 组件中做到这一点?

原文由 samuel toh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

更新:我建议使用@Jess 提供的带有过滤器的解决方案。

我会为此编写一个方法,然后在您需要格式化价格的地方,您可以将该方法放在模板中并向下传递值

methods: {
    formatPrice(value) {
        let val = (value/1).toFixed(2).replace('.', ',')
        return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")
    }
}

然后在模板中:

 <template>
    <div>
        <div class="panel-group"v-for="item in list">
            <div class="col-md-8">
                <small>
                   Total: <b>{{ formatPrice(item.total) }}</b>
                </small>
            </div>
        </div>
    </div>
</template>

顺便说一句 - 我并没有太在意替换和正则表达式。它可以改进。 enter code here

 Vue.filter('tableCurrency', num => {
  if (!num) {
    return '0.00';
  }
  const number = (num / 1).toFixed(2).replace(',', '.');
  return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
});

原文由 Belmin Bedak 发布,翻译遵循 CC BY-SA 4.0 许可协议

我创建了一个过滤器。过滤器可以在任何页面中使用。

 Vue.filter('toCurrency', function (value) {
    if (typeof value !== "number") {
        return value;
    }
    var formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    });
    return formatter.format(value);
});

然后我可以像这样使用这个过滤器:

         <td class="text-right">
            {{ invoice.fees | toCurrency }}
        </td>

我使用这些相关答案来帮助实现过滤器:

原文由 Jess 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题