Skip to content

Commit

Permalink
feat: add fallback locale
Browse files Browse the repository at this point in the history
  • Loading branch information
niutech committed Jul 13, 2021
1 parent 22b2490 commit e085e3b
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import App from './App.vue';

const i18n = createI18n({
locale: 'en',
fallbackLocale: 'en',
messages: {
'en': {
home: 'Home'
Expand All @@ -33,6 +34,7 @@ export default {
const i18n = useI18n()
i18n.createI18n({
locale: 'en',
fallbackLocale: 'en',
messages: {
'en': {
home: 'Home'
Expand Down
12 changes: 7 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ import { vueI18nKey } from './injectionSymbols'
* @param options - {@link I18nOptions}
*/
export function createI18n(options?: I18nOptions): I18n {
const initOptions = Object.assign({ locale: 'en', messages: {} }, options)
const initOptions = Object.assign(
{ locale: 'en', fallbackLocale: 'en', messages: {} },
options
)
const current = ref(initOptions.locale)
const locales: I18nLocales = initOptions.messages

Expand All @@ -33,11 +36,10 @@ export function createI18n(options?: I18nOptions): I18n {

const locale =
typeof option === 'string' && option ? option : current.value
if (!locales[locale]) {
return key
}

let message = getMessage(locales[locale], key)
let message =
getMessage(locales[locale], key) ||
getMessage(locales[initOptions.fallbackLocale], key)
if (option && typeof option !== 'string') {
const values = parseLocaleValues(message, option)
if (!isEmpty(values)) {
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { DeepReadonly, UnwrapNestedRefs } from '@vue/reactivity'
*/
export type I18nOptions = {
locale?: string
fallbackLocale?: string
messages?: I18nLocales
}

Expand Down

0 comments on commit e085e3b

Please sign in to comment.