Search code examples
vue.jsvuejs3vue-i18n

How to use currency formatting at i18n + Vue 3?


I have {{n (100, "currency")}} and I would like to display it as $100 - but how can I get n correctly? For example when I'm using

import { useI18n } from "vue-i18n";

 setup() {
    const { t, n } = useI18n({
      locale: "en-US",

      numberFormats: {
        "en-US": {
          currency: {
            style: "currency",
            currency: "USD",
          },
        },
      },
    });

    return { t, n };
  },

I get an error Uncaught (in promise) SyntaxError: Invalid arguments How can I solve this problem


Solution

    1. VueI18n must be initialized 1st by using createI18n and app.use()
    2. To use composition API, the legacy: false must be used

    See example below. Note that VueI18n.createI18n or Vue.createApp in the example is used because scripts are loaded from CDN. When used with bundler, just use import and use createApp or createI18n directly...

    const i18n = VueI18n.createI18n({
      legacy: false,
      locale: "en-US",
      numberFormats: {
        "en-US": {
          currency: {
            style: "currency",
            currency: "USD",
          },
        },
      },
    })
    
    const app = Vue.createApp({
      setup() {
        const { n } = VueI18n.useI18n()
        return { n }
      }
    })
    app.use(i18n)
    app.mount("#app")
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/vue-i18n@next"></script>
    <div id="app">
      {{ n(100, "currency") }}
    </div>