Vue項目通過vue-i18n實現(xiàn)國際化方案(推薦)
Vue I18n官網(wǎng) :Vue I18n
1、安裝:
npm install vue-i18n --save
說明:直接下載最新版本的時候,出現(xiàn)了一個報錯,后來換回了低一點的版本(如:8.22.1版本),就沒出現(xiàn)把報錯了,具體的報錯如下:
Uncaught TypeError: Cannot read properties of undefined (reading ‘install‘) 頁面一片空白
(具體原因目前還沒排查處理,如果大家有解決方案,歡迎評論留言~)
2、配置:
在src文件夾下,新建plugins文件夾,里邊有兩個語言文件包:en.json(英文語言包) 、zh.json(中文語言包)目錄如圖:
en.json文件:
{
"login": {
"loginBtn": "LOGIN",
"loginTitle": "User Login",
"userName": "Please enter username!",
"password": "Please enter password!"
}
}
zh.json文件:
{
"login": {
"loginBtn": "登錄",
"loginTitle": "用戶登錄",
"userName": "請輸入用戶名",
"password": "請輸入密碼"
}
}
i18n.js文件:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
function loadLocaleMessages() {
const locales = require.context('./lang', true, /[A-Za-z0-9-_,\s]+\.json$/i) // 在vue項目中使用require.context()引入某個文件夾下所有文件
console.log('locales:', locales)
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 || 'zh', // 設(shè)置頁面的默認語言
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'zh',
messages: loadLocaleMessages()
})
此外,還要在vue.config.js文件中,配置以下內(nèi)容:
pluginOptions: {
i18n: {
locale: 'en',
fallbackLocale: 'en',
localeDir: 'i18n',
enableInSFC: true
}
},
main.js文件引入i18n
import i18n from './plugins/i18n/i18n.js' // 使用i18n實現(xiàn)國際化
console.log('i18n:', i18n)
i18n.locale = 'zh' // 初始化i18n,默認英文顯示
new Vue({
router,
store,
i18n,
render: h => h(App)
}).$mount('#baseApp')
3、使用:
<el-button :loading="loading" type="primary" @click="subLogin">{{ $t('login.loginBtn') }}</el-button>
4、注意:語言包文件的數(shù)據(jù)持久化。
5、在xx.js文件中使用i18n的注意事項:
(方法一):在main.js把Vue對象賦值給一個window上的一個對象vm
window.vm = new Vue({
el: '#app',
i18n,
router,
store,
template: '<App/>',
components: { App }
})
使用的時候就這樣用 :

(方法二):

存在的問題:上面的是關(guān)于登錄表單的校驗,如第一次默認語言是中文,能正確顯示校驗提示,但是切換語言后,比如英文,校驗提示還是顯示中文,并沒有同步切換回英文。
解決方案:
到此這篇關(guān)于Vue項目通過vue-i18n實現(xiàn)國際化方案的文章就介紹到這了,更多相關(guān)Vue vue-i18n實現(xiàn)國際化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Vue如何實現(xiàn)顏色選擇與調(diào)色板功能
顏色選擇和調(diào)色板是Web開發(fā)中常用的功能,Vue作為一個流行的JavaScript框架,可以方便地實現(xiàn)顏色選擇和調(diào)色板功能,本文講講如何在Vue中進行顏色選擇和調(diào)色板吧2023-06-06
Vue中使用iframe踩坑問題記錄 iframe+postMessage
這篇文章主要介紹了Vue中使用iframe踩坑問題記錄 iframe+postMessage,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
一文搞懂Vue3中toRef和toRefs函數(shù)的使用
這篇文章主要為大家介紹了Vue3中toRef和toRefs函數(shù)的使用方法,文中通過示例為大家進行了詳細的講解,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-07-07

