如何在VUE應用中實施國際化(I18N)?
安裝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 應用的多語言支持。
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.

✅ Step 1: Install Vue I18n
For Vue 3 (use Vue I18n v9 ):
npm install vue-i18n@next
For Vue 2 (use Vue I18n v8):

npm install vue-i18n
✅ Step 2: Prepare Language Files
Create a folder (eg, locales
) to store translation files.
Example: locales/en.json

{ "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('greeting') }}</p> <p>{{ $t('description') }}</p> <p>{{ $t('home.welcome', { name: 'Alice' }) }}</p> </div> </template>
In JavaScript (Vue 3 Composition API):
import { useI18n } from 'vue-i18n' export default { setup() { const { t } = useI18n() console.log(t('greeting')) return { t } } }
In Vue 2 Options API:
export default { created() { console.log(this.$t('greeting')) } }
✅ 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('en')">English</button> <button @click="changeLocale('es')">Español</button>
Note: In Vue 3 with
createI18n
, you may need to usei18n.global.locale.value = lang
if using the global instance.
import { i18n } from './i18n' i18n.global.locale.value = 'es'
✅ Optional: Lazy Load Translations (for large apps)
To reduce bundle size, load translations on demand:
const messages = { en: () => import('../locales/en.json'), es: () => import('../locales/es.json') } const i18n = createI18n({ locale: 'en', fallbackLocale: 'en', 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('es') ? 'es' : 'en' 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中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

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

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

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

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

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

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

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

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

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

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

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

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