首頁  >  文章  >  web前端  >  如何使用Vue實現多語言和國際化?

如何使用Vue實現多語言和國際化?

WBOY
WBOY原創
2023-06-27 21:39:402576瀏覽

隨著全球化的發展,多語言和國際化越來越成為一個網站或應用程式的必要功能之一。 Vue作為一個受歡迎的前端框架,在這方面也有著靈活的解決方案。本文將介紹如何使用Vue實現多語言和國際化。

一、安裝Vue-i18n

Vue-i18n是Vue.js的國際插件,可以幫助我們實現多語言和國際化。首先需要在專案中安裝Vue-i18n。

npm install vue-i18n --save

二、建立語言檔案

在專案中建立一個i18n資料夾,用於存放語言檔案。

在i18n資料夾中建立一個名為index.js的文件,用於配置Vue-i18n。

import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

const i18n = new VueI18n({
  locale: 'en', // 默认使用英文
  messages: {
    en: require('./en.json'),
    zh: require('./zh.json'),
  },
});

export default i18n;

上述程式碼中,locale表示目前使用的語言,預設使用英文。 messages表示使用的語言文件,這裡分別引入了en.json(英文)和zh.json(中文)。

現在可以在i18n資料夾中建立en.json和zh.json文件,並編寫語言內容。

en.json

{
  "hello": "Hello",
  "world": "World",
  "welcome": "Welcome"
}

zh.json

{
  "hello": "你好",
  "world": "世界",
  "welcome": "欢迎"
}

三、使用Vue-i18n

在元件中使用Vue-i18n非常簡單,只需要在模板中加入$tc(翻譯)或$t(格式化)即可。

<template>
  <div>
    <p>{{ $t('hello') }}</p>
    <p>{{ $tc('world', 1) }}</p>
    <p>{{ greeting }}</p>
  </div>
</template>

<script>
import i18n from '@/i18n';

export default {
  computed: {
    greeting() {
      return this.$t('welcome', { name: 'Vue' });
    },
  },
  created() {
    // 设置语言为中文
    i18n.locale = 'zh';
  },
};
</script>

上述程式碼中,$t和$tc都可以用於翻譯,差別在於$t可以進行格式化,$tc可以根據參數進行複數化。這裡也示範了computed屬性中使用$t方法,以及在元件created生命週期中修改語言。

四、使用Vue CLI外掛程式

Vue CLI提供了官方外掛程式vue-cli-plugin-i18n,可以快速整合多語言和國際化。

首先需要安裝外掛程式。

vue add i18n

安裝成功後,會在專案中產生locales資料夾,用於存放語言檔案。

修改src/i18n.js檔。

import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

function loadLocaleMessages() {
  const locales = require.context('@/locales', true, /[A-Za-z0-9-_,s]+.json$/i);
  const messages = {};
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  });
  return messages;
}

export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages(),
  silentFallbackWarn: true,
});

在上述程式碼中,loadLocaleMessages函數用於自動載入locales資料夾中的語言文件,並傳回messages物件。此外,還可以透過環境變數VUE_APP_I18N_LOCALE和VUE_APP_I18N_FALLBACK_LOCALE設定預設語言和回退語言。

在元件中使用$te方法判斷鍵值是否存在,$d方法進行日期格式化。

<template>
  <div>
    <p v-if="$te('hello')">Hello</p>
    <p>{{ $d(new Date(), 'short') }}</p>
  </div>
</template>

<script>
export default {};
</script>

以上就是使用Vue實現多語言和國際化的基本方法。透過Vue-i18n插件或Vue CLI插件,可以輕鬆實現多語言和國際化功能,讓網站或應用程式更符合全球化的趨勢。

以上是如何使用Vue實現多語言和國際化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn