這是我的代碼,可以正常作業:
import { createI18n } from 'vue-i18n'
import messages from './components/json/foo/foo_messages.json'
const app = createApp(App)
installI18n(app)
const i18n = createI18n({
locale: 'ru',
messages
})
app
.use(i18n)
.use(vuetify)
.mount('#app')
現在我還需要從./components/json/bar/bar_messages.json. 我試圖這樣做:
import { createI18n } from 'vue-i18n'
import foo_msg from './components/json/foo/foo_messages.json'
import bar_msg from './components/json/bar/bar_messages.json'
const app = createApp(App)
installI18n(app)
const i18n = createI18n({
locale: 'ru',
messages: {foo_msg, bar_msg}
})
app
.use(i18n)
.use(vuetify)
.mount('#app')
但它沒有用。誰能說說怎么做?
編輯:這是我的 foo json 檔案
{
"ru": {
"header": {
"hello": "Привет"
}
},
"en": {
"header": {
"hello": "Hello"
}
}
}
這是條 json 檔案
{
"ru": {
"footer": {
"bye": "Пока"
}
},
"en": {
"footer": {
"bye": "Goodbye"
}
}
}
uj5u.com熱心網友回復:
您嘗試做的不是很可擴展。鑒于 i18n JSON 訊息的格式,您需要將輸入檔案合并為如下內容:
{
"ru": {
"header": {
"hello": "Привет"
},
"footer": {
"bye": "Пока"
}
},
"en": {
"header": {
"hello": "Hello"
},
"footer": {
"bye": "Goodbye"
}
}
}
...這對于 JS 來說絕對是可能的,但是你仍然必須為你的每個組件匯入 JSON 檔案,main.js這既乏味又容易出錯
您是否考慮過在您的組件中使用 vue-i18n自定義塊?您甚至可以將翻譯保存在外部 JSON 檔案中并使用自定義塊,例如<i18n src="./myLang.json"></i18n>
這是更好的方法,但如果您仍然想使用您的方法,這里有一個簡單的代碼,如何將所有翻譯檔案(從 JSON 匯入的物件)合并到 vue-i18n 可用的單個物件中:
// import foo_msg from './components/json/foo/foo_messages.json'
const foo_msg = {
"ru": {
"header": {
"hello": "Привет"
}
},
"en": {
"header": {
"hello": "Hello"
}
}
}
// import bar_msg from './components/json/bar/bar_messages.json'
const bar_msg = {
"ru": {
"footer": {
"bye": "Пока"
}
},
"en": {
"footer": {
"bye": "Goodbye"
}
}
}
const sources = [foo_msg, bar_msg]
const messages = sources.reduce((acc, source) => {
for(key in source) {
acc[key] = { ...(acc[key] || {}), ...source[key] }
}
return acc
},{})
console.log(messages)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402893.html
標籤:
上一篇:Vuetifyv-btn文本行為
