目錄
✅ Step 1: Install Vue I18n
✅ Step 2: Prepare Language Files
✅ Step 3: Set Up i18n in Your App
For Vue 3 (Composition API):
For Vue 2 (Options API):
✅ Step 4: Use Translations in Components
In Templates:
In JavaScript (Vue 3 Composition API):
In Vue 2 Options API:
✅ Step 5: Change Language at Runtime
✅ Optional: Lazy Load Translations (for large apps)
✅ Bonus: Detect User's Preferred Language
Summary
首頁 web前端 Vue.js 如何在VUE應用中實施國際化(I18N)?

如何在VUE應用中實施國際化(I18N)?

Jul 26, 2025 am 08:37 AM
vue 國際化

安裝Vue I18n:Vue 3 使用npm install vue-i18n@next,Vue 2 使用npm install vue-i18n;2. 在locales 目錄下創建語言文件如en.json 和es.json,支持嵌套結構;3. 在Vue 3 中通過createI18n 創建實例並在main.js 中掛載,Vue 2 中通過Vue.use(VueI18n) 並實例化VueI18n;4. 模板中使用{{ $t('key') }} 插值,Vue 3 Composition API 中使用useI18n 的t 函數,Vue 2 Options API 中使用this.$t;5. 通過this.$i18n.locale = lang(Vue 2)或i18n.global.locale.value = lang(Vue 3)實現運行時語言切換;6. 可選地通過動態導入實現翻譯文件的懶加載以優化性能;7. 可通過navigator.language 檢測用戶瀏覽器語言並自動設置locale;通過以上步驟,可完整實現Vue 應用的多語言支持。

How to implement internationalization (i18n) in a Vue app?

Implementing internationalization (i18n) in a Vue app is straightforward with the help of Vue I18n , the official internationalization plugin. Here's how to set it up step by step for both Vue 3 and Vue 2.

How to implement internationalization (i18n) in a Vue app?

✅ Step 1: Install Vue I18n

For Vue 3 (use Vue I18n v9 ):

 npm install vue-i18n@next

For Vue 2 (use Vue I18n v8):

How to implement internationalization (i18n) in a Vue app?
 npm install vue-i18n

✅ Step 2: Prepare Language Files

Create a folder (eg, locales ) to store translation files.

Example: locales/en.json

How to implement internationalization (i18n) in a Vue app?
 {
  "greeting": "Hello!",
  "description": "Welcome to our application."
}

Example: locales/es.json

 {
  "greeting": "¡Hola!",
  "description": "Bienvenido a nuestra aplicación."
}

You can also support nested structures:

 {
  "home": {
    "title": "Home Page",
    "welcome": "Welcome, {name}!"
  }
}

✅ Step 3: Set Up i18n in Your App

For Vue 3 (Composition API):

Create i18n.js or i18n/index.js :

 import { createI18n } from 'vue-i18n'
import en from '../locales/en.json'
import es from '../locales/es.json'

const messages = {
  en,
  es
}

const i18n = createI18n({
  locale: 'en', // default locale
  fallbackLocale: 'en',
  messages
})

export default i18n

Then, in your main.js :

 import { createApp } from 'vue'
import App from './App.vue'
import i18n from './i18n'

createApp(App).use(i18n).mount('#app')

For Vue 2 (Options API):

In main.js :

 import Vue from 'vue'
import VueI18n from 'vue-i18n'
import en from './locales/en.json'
import es from './locales/es.json'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages: { en, es }
})

new Vue({
  i18n,
  render: h => h(App)
}).$mount('#app')

✅ Step 4: Use Translations in Components

In Templates:

 <template>
  <div>
    <p>{{ $t(&#39;greeting&#39;) }}</p>
    <p>{{ $t(&#39;description&#39;) }}</p>
    <p>{{ $t(&#39;home.welcome&#39;, { name: &#39;Alice&#39; }) }}</p>
  </div>
</template>

In JavaScript (Vue 3 Composition API):

 import { useI18n } from &#39;vue-i18n&#39;

export default {
  setup() {
    const { t } = useI18n()
    console.log(t(&#39;greeting&#39;))
    return { t }
  }
}

In Vue 2 Options API:

 export default {
  created() {
    console.log(this.$t(&#39;greeting&#39;))
  }
}

✅ Step 5: Change Language at Runtime

Add a method to switch languages dynamically:

 // In a component
methods: {
  changeLocale(lang) {
    this.$i18n.locale = lang
  }
}
 <button @click="changeLocale(&#39;en&#39;)">English</button>
<button @click="changeLocale(&#39;es&#39;)">Español</button>

Note: In Vue 3 with createI18n , you may need to use i18n.global.locale.value = lang if using the global instance.

 import { i18n } from &#39;./i18n&#39;
i18n.global.locale.value = &#39;es&#39;

✅ Optional: Lazy Load Translations (for large apps)

To reduce bundle size, load translations on demand:

 const messages = {
  en: () => import(&#39;../locales/en.json&#39;),
  es: () => import(&#39;../locales/es.json&#39;)
}

const i18n = createI18n({
  locale: &#39;en&#39;,
  fallbackLocale: &#39;en&#39;,
  messages
})

Vue I18n will handle async loading automatically.


✅ Bonus: Detect User's Preferred Language

Use browser language detection:

 const userLang = navigator.language || navigator.userLanguage
const locale = userLang.startsWith(&#39;es&#39;) ? &#39;es&#39; : &#39;en&#39;
i18n.global.locale.value = locale

Summary

  • Use vue-i18n for translations.
  • Store translations in JSON files.
  • Set up the i18n instance and plug it into Vue.
  • Use $t() in templates and code.
  • Change locale dynamically.
  • Optionally lazy-load translations and detect browser language.

With this setup, your Vue app can support multiple languages cleanly and efficiently.基本上就這些。

以上是如何在VUE應用中實施國際化(I18N)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

Rimworld Odyssey溫度指南和Gravtech
1 個月前 By Jack chen
初學者的Rimworld指南:奧德賽
1 個月前 By Jack chen
PHP變量範圍解釋了
4 週前 By 百草
撰寫PHP評論的提示
3 週前 By 百草
在PHP中評論代碼
3 週前 By 百草

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1604
29
PHP教程
1509
276
Vue的反應性轉換(實驗,然後被刪除)的意義是什麼? Vue的反應性轉換(實驗,然後被刪除)的意義是什麼? Jun 20, 2025 am 01:01 AM

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

VUE中的服務器端渲染SSR是什麼? VUE中的服務器端渲染SSR是什麼? Jun 25, 2025 am 12:49 AM

Server-Serdendering(SSR)InvueImProvesperformandSeobyGeneratingHtmlonTheserver.1.TheserverrunsvueApcodeAmpCodeAndGeneratesHtmlbBasedonThecurrentRoute.2.thathtmlssenttothebrowserimmed.3.vuehirative eveirtive eveirtive eveirtive eveirtive eveirtive eveirtive eveirtive eveirtiveThepage evepage evepage

如何使用VUE構建組件庫? 如何使用VUE構建組件庫? Jul 10, 2025 pm 12:14 PM

搭建Vue組件庫需圍繞業務場景設計結構,並遵循開發、測試、發布的完整流程。 1.結構設計應按功能模塊分類,包括基礎組件、佈局組件和業務組件;2.使用SCSS或CSS變量統一主題與樣式;3.統一命名規範並引入ESLint和Prettier保證代碼風格一致;4.配套文檔站點展示組件用法;5.使用Vite等工具打包為NPM包並配置rollupOptions;6.發佈時遵循semver規範管理版本與changelog。

如何在VUE中實現過渡和動畫? 如何在VUE中實現過渡和動畫? Jun 24, 2025 pm 02:17 PM

ToaddtransitionsandanimationsinVue,usebuilt-incomponentslikeand,applyCSSclasses,leveragetransitionhooksforcontrol,andoptimizeperformance.1.WrapelementswithandapplyCSStransitionclasseslikev-enter-activeforbasicfadeorslideeffects.2.Useforanimatingdynam

如何用PHP開發問答社區平台 PHP互動社區變現模式詳解 如何用PHP開發問答社區平台 PHP互動社區變現模式詳解 Jul 23, 2025 pm 07:21 PM

1.PHP開發問答社區首選Laravel MySQL Vue/React組合,因生態成熟、開發效率高;2.高性能需依賴緩存(Redis)、數據庫優化、CDN和異步隊列;3.安全性必須做好輸入過濾、CSRF防護、HTTPS、密碼加密及權限控制;4.變現可選廣告、會員訂閱、打賞、佣金、知識付費等模式,核心是匹配社區調性和用戶需求。

如何用PHP開發AI智能表單系統 PHP智能表單設計與分析 如何用PHP開發AI智能表單系統 PHP智能表單設計與分析 Jul 25, 2025 pm 05:54 PM

選擇合適的PHP框架需根據項目需求綜合考慮:Laravel適合快速開發,提供EloquentORM和Blade模板引擎,便於數據庫操作和動態表單渲染;Symfony更靈活,適合複雜系統;CodeIgniter輕量,適用於對性能要求較高的簡單應用。 2.確保AI模型準確性需從高質量數據訓練、合理選擇評估指標(如準確率、召回率、F1值)、定期性能評估與模型調優入手,並通過單元測試和集成測試保障代碼質量,同時持續監控輸入數據以防止數據漂移。 3.保護用戶隱私需採取多項措施:對敏感數據進行加密存儲(如AES

VUE中的自定義插件是什麼? VUE中的自定義插件是什麼? Jun 26, 2025 am 12:37 AM

要創建一個Vue自定義插件,請按以下步驟操作:1.定義包含install方法的插件對象;2.在install中通過添加全局方法、實例方法、指令、混入或註冊組件來擴展Vue;3.導出插件以便在其他地方導入使用;4.在主應用文件中通過Vue.use(YourPlugin)註冊插件。例如,可創建一個為所有組件添加$formatCurrency方法的插件,在install中設置Vue.prototype.$formatCurrency。使用插件時應注意避免過度污染全局命名空間、減少副作用,並確保每個插件

Vue成品資源網站免費入口 完整Vue成品永久在線觀看 Vue成品資源網站免費入口 完整Vue成品永久在線觀看 Jul 23, 2025 pm 12:39 PM

本文為Vue開發者和學習者精選了一系列頂級的成品資源網站。通過這些平台,你可以免費在線瀏覽、學習甚至復用海量高質量的Vue完整項目,從而快速提升開發技能和項目實踐能力。

See all articles