javascript - 如何使用 BootstrapVue 将值格式化为货币?

标签 javascript vue.js

我需要使用 bootstrap-vue 格式化程序(b-table - 字段)将值格式化为货币。

我目前的尝试:

fields: [
    { key: 'value', label: 'value(R$)', sortable: true,
        formatter: (value, key, item) => {
            return Number(item.value).toLocaleString('pt-BR', {
                style: 'decimal', currency: 'BRL'
            })
        }
    },
]

我需要以某种方式格式化从后端(axios)获得的这些值。

可以帮助我吗?

最佳答案

要使用 toLocaleString 将数字格式化为货币,您需要使用 style: 'currency' 选项。

您可以阅读有关toLocaleString的更多信息here 。 如果您向下滚动到示例,然后继续向下滚动到 using options 部分,您将看到 style: 'currency' 选项的几个示例。这是我找到信息的地方。

对于不同的选项,您还可以引用Intl.NumberFormat参数部分。

请注意,这不会进行任何货币转换。

请参阅下面的代码片段。

new Vue({
  el: '#app',
  data() {
    return {
      items: [
        { value: 123.45 },
        { value: 23 },
        { value: 12.6 }
      ],
      fields: [
          { key: 'value', label: 'value(R$)', sortable: true,
              formatter: (value, key, item) => value.toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'})
          },
      ]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.5.0/dist/bootstrap-vue.min.js"></script>

<link href="https://unpkg.com/bootstrap-vue@2.5.0/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap@4.3.1/dist/css/bootstrap.min.css" rel="stylesheet" />

<div id="app">
  <b-table :items="items" :fields="fields"></b-table>
</div>

关于javascript - 如何使用 BootstrapVue 将值格式化为货币?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60602818/

相关文章:

vue.js - Vue单文件组件中如何导入和使用图片?

javascript - ES6 中对象的高级解构

javascript - 在 MVC 中提交按钮时如何重定向到另一个 tabpanel 选项卡

javascript - 检查 Javascript 中是否存在一个值

javascript - ASP.NET Core SignalR 中的客户端生命周期事件

javascript - 如何将对象从数据属性传递到VueJS中的方法

javascript - JS根据数字显示数组值

javascript - Vee-validate 和 Vuetify 出现问题,渲染错误 : "TypeError: Cannot read property ' $vuetify' of null"

javascript - 是否可以获取组件中指定的引用名称? Vue.js

vue.js - 如何在 html 中使用 .vue 文件?