Home  >  Q&A  >  body text

Using Vue-i18n, how can I not display anything until the message is dynamically loaded?

In our Vue application, we load translations dynamically. Our strings will appear as codes/expressions before they arrive from the server.

Is there some way to tell Vue-i18n to default to blank if no message is loaded? Or can I override something to return an empty string?

P粉930534280P粉930534280282 days ago372

reply all(1)I'll reply

  • P粉087951442

    P粉0879514422024-01-11 09:05:44

    You can achieve this by adding the fallbackLocale attribute in the VueI18n initialization.

    As in the demo below, locale ja is not available, therefore, it loads fallbackLocale (I added empty strings in all properties of the default locale).

    Live Demo:

    const messages = {
      en: {
        message: {
          tokyo: 'Tokyo',
          newyork: 'New York',
          london: 'London'
        }
      },
      default: {
        message: {
          tokyo: '',
          newyork: '',
          london: ''
        }
      }
    }
    const i18n = new VueI18n({
      locale: 'ja',
      fallbackLocale: 'default',
      messages,
    })
    new Vue({
      i18n,
      data: {cities: ['tokyo', 'newyork', 'london']}
    }).$mount('#app')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-i18n/8.14.1/vue-i18n.min.js"></script>
    <div id="app">
      <ul>
        <li
          v-for="city in cities"
          :key="city">
          {{city}}: {{ $t("message." + city) }}
        </li>
      </ul>
    </div>

    reply
    0
  • Cancelreply