vue-i18n@10

LeeWonjin·2025년 2월 2일

https://vue-i18n.intlify.dev/guide/introduction.html

시작하기

설치

npm install vue-i18n@10
// main.js
import { createI18n } from 'vue-i18n';
const i18n = createI18n({});
app.use(i18n);

기본 원리

locale은 현재 선택된 로케일,
fallbackLocale은 못찾는 로케일 선택되면 사용할 로케일
messages안에 로케일별로 내용을 집어넣는다 (en, ko)

컴포넌트에서 쓸 때는 $t('아이템 키')처럼 한다.
locale값에 해당하는 키의 값을 가져와 보여줌.

// main.js
...
const options = {
	locale: 'ko',
    fallbackLocale: 'en',
  	messages: {
    	en: {
           	helloworld: 'Hello World',
          	nested: {
            	item: 'hi',
            }
        },
      	ko: {
            helloworld: '안녕 세계',
          	nested: {
            	item: 'ㅎㅇ',
            }
        },
    }
}
const i18n = createI18n(options);
app.use(i18n);
...

// App.js
<span>
      {{ $t('helloworld') }}   
      {{ $t('nested.item') }}
</span>

Format syntax, Translation

옵션은 한 개 로케일 안의 내용만 쓴다.

Named interpolation

// option
{
	msg: 'I am {name}'
}

// ui
$t('msg', {name: 'Alice'}) // I am Alice

List interpolation

// option
{
	msg: '{0} is not {1}'
}

// ui
$t('msg', ['A', 'B']) // A is not B

Literal interpolation

특수하게 사용되는 문자를 그대로 표시하고 싶을 때 (c의 \% escape string처럼)

  • Format syntax에서 특수하게 취급되는 문자는 { } @ % |
// option -- use '@' literal
msg: "{'@'}{location}"

// ui
$t('msg', {location: 'Seoul'})

Linked message

// option
last_name: '이',
first_name: '원진',
full_name: '@:last_name @:first_name'

// ui
$t('full_name') // 이 원진

modifiers

@.modifier:key 로 쓴다

Built-in modifiers

// option
name: 'aBc'
msg: '@.upper:name @.lower:name @.capitalize:name'

// ui
$t('msg') // ABC abc Abc

Custom modifiers

// option
{
	locale: 'en',
    messages: {
    	en: { 
          	greet: 'hello world',
        	msg: '@.onlyFirstWord:greet'
        }
        ko: { ... } 
    },
    modifiers: {
    	onlyFirstWord: (str) => str.split(' ')[0]
    }
}
  
// ui
$t('msg') // hello

Pluralization

| pipe 사용해서 단복수 표현 정의함

  • A|B : 1개일 때 A, 0개 또는 2개 이상이면 B
  • A|B|C : 0개일 때 A, 1개일 때 B, 2개 이상일 때 C

Basic usage

// option
car: 'car | cars',
bike: 'no bike | bike | bikes'

// ui 
$t('car', 0) // cars
$t('car', 1) // car
$t('car', 2) // cars

$t('bike', 0) // no bike
$t('bike', 1) // bike
$t('bike', 2) // bikes

Predefined implicit arguments

plural 메시지 신택스에서 n, count를 사용해 개수 표시 가능
$t에서 넣어줄 때는 방법 두가지

  • 2번째 인수 숫자로 그냥 주든가
  • 3번째 object 인수로 주든가 {named: { n: 2, count: '문자도 됨'}}

named로 주는거 아니면 메시지에서 둘 중 아무거나 써도 됨.

// option
baguette: 'une baguette | {n} baguettes',
pain: 'sans pain | un pain | {count} pains',

// ui
$t('baguette', 10) // 10 baguettes
$t('baguette', 1) // une baguette

$t('pain', 0) // sans pain
$t('pain', 1) // un pain
$t('pain', 10) // 10 pains
$t('pain', 10, { named: { count: 10 } }) // 10 pains
$t('pain', 60, { named: { count: 2 } }) // 2 pains

Custom Rules

https://vue-i18n.intlify.dev/guide/essentials/pluralization.html#custom-pluralization

Datetime Formatting

https://tc39.es/ecma402/#datetimeformat-objects

  • createI18n 옵션의 datetimeFormats로 넣어준다. (번역은 messages였던 반면)
  • 로케일별로 short, long처럼 표시 유형 이름 정하고, 그 안에 year, month, day, weekday, hour, minute, hour12 형식 정해준다.
  • ui에서 꺼내쓸 때는 $d로 한다. (번역은 $t였던 반면)

Basic usage

// option
const datetimeFormats = {
  'en-US': {
    short: {
      year: 'numeric', month: 'short', day: 'numeric'
    },
    long: {
      year: 'numeric', month: 'short', day: 'numeric',
      weekday: 'short', hour: 'numeric', minute: 'numeric'
    }
  },
  'ko-KR': {
  	...
  },
};

const i18n = createI18n({
	locale: 'en-US',
  	messages: { ... },
    datetimeFormats,
});

// ui

/* Sun, Feb 2, 2025, 10:00 PM */
<span> {{ $d(new Date(), 'long') }} </span>

/* Feb 2, 2025 */
<span>  {{ $d(new Date(), 'short') }} </span>

Custom format

<i18n-d> </i18n-d> 컴포넌트를 사용하면 각 부분을 포맷팅할 수 있다.
그러나 기본 날짜 스트링의 부분을 태그로 만드는 것에 그친다.
완전한 커스텀이 되지 않는 것 같음.

결국 완전한 맞춤형 날짜 포맷팅을 하고 싶다면 직접 구현하는게 빠른듯.

Number Formatting

https://tc39.es/ecma402/#numberformat-objects

createI18n 옵션의 numberFormats을 넣어줘야 함.
$n() 사용.

Custom format

<i18n-n>컴포넌트로 할 수 있다.

기타

  • fallback은 로케일별로 해줄 수 있음. 여러개 할 수도 있음.
    • implicit fallback도 있고, explicit fallback도 있다.
    • implicit fallback예시 링크
  • global, local스코프가 있음.
    • local스코프의 메시지들을 따로 정해줄 수도 있음
    • 로컬에서 키 못찾으면 글로벌로 올라가서 찾음.
  • 로케일 변경은 (링크)
    • vue컴포넌트에서: $i18n.locale로 접근 가능.
    • js로 : i18n.global.locale.value로 접근 가능
  • SFC에서 <i18n> 커스텀태그로 로컬 로케일 설정 가능
  • Lazy Loading가능
  • Component Interpolation 가능 (여러 태그에 걸쳐서 지역화)
  • Composition API 있음 (import { useI18n } ...)
  • Web Components됨. Typescript됨.
  • 커스텀 메시지 포맷 지정 가능함.
  • 번역기능($t)만 쓰고 싶으면 경량화된 버전인 Petite vue i18n도 옵션임.
  • message function으로도 됨. 꼭 중괄호로 하는 message 보간 아니어도.
profile
노는게 제일 좋습니다.

0개의 댓글