I18n 라이브러리를 통해 다국어를 지원하는 방법과
줄바꿈 하는 방법 기록하기!!
https://vue-i18n.intlify.dev/guide/installation.html
# I18n 사용법
1. I18n 설치
npm install vue-i18n@9
2. 번역 될 파일 생성하기
appLocale.ts 파일을 따로 만들었고,
messages 최상위 객체 안에
locale (jp, en, kr),
message,
key-value (hello: '안녕')
순으로 작성해준다.
// appLocale.ts
export default {
messages: {
jp: {
message: {
hello: 'こんにちは'
}
},
en: {
message: {
hello: 'hi'
}
},
kr: {
message: {
hello: '앙뇽'
}
},
}
}
3. main.ts에 I18n 인스턴스 생성하기
저는 프로젝트 구조가 plugins/index.ts를 main.ts에서 불러오도록 되어있어서,
plugins/index.ts 요 파일에 인스턴스를 생성했습니다!
전체 코드를 보기 전 인스턴스 생성부분만 살펴보자면!
legacy : false ➡️ composition API 사용을 위해
allowComposition : true ➡️ 공식문서에서 이렇게 하래요,,
locale : 'kr' ➡️ 사용자 인터페이스에서 사용되는 기본 언어 '한국어'
locale : 'en' ➡️ 기본 언어 표시에 문제가 있을 경우 대체할 언어 '영어'
messages: appLocale.messages ➡️ 번역할 메세지..? appLocale.ts 파일에서 작성한 messages 객체
// 2. Create i18n instance with options
export const i18n = createI18n({
legacy: false, // you must set `false`, to use Composition API
allowComposition: true, // you need to specify that!
locale: 'kr', // set locale
fallbackLocale: 'en', // set fallback locale
messages: appLocale.messages, // set locale messages
// If you need to specify other options, you can set other options
// ...
});
전체코드
/**
* plugins/index.ts
*
* Automatically included in `./src/main.ts`
*/
// Plugins
import vuetify from './vuetify';
import pinia from '../store';
import router from '../router';
import AOS from 'aos';
import 'aos/dist/aos.css';
import axios from 'axios';
// I18n import 하기!!
import { createI18n } from 'vue-i18n';
// 앞서 만든 appLocale.ts 파일 import 하기!
import appLocale from '@/appLocale';
// Types
import type { App } from 'vue';
// Global
import { global } from '@/commonGlobal/global';
// 1. Ready translated locale messages
// The structure of the locale message is the hierarchical object structure with each locale as the top property
// 메세지 파일은 appLocale.ts 파일로 따로 분리했습니다!
// 2. Create i18n instance with options
export const i18n = createI18n({
legacy: false, // you must set `false`, to use Composition API
allowComposition: true, // you need to specify that!
locale: 'kr', // set locale
fallbackLocale: 'en', // set fallback locale
messages: appLocale.messages, // set locale messages
// If you need to specify other options, you can set other options
// ...
});
export function registerPlugins(app: App) {
app.use(vuetify).use(router).use(pinia).use(global).use(i18n);
const resourceHost = import.meta.env.VITE_HOST;
axios.defaults.baseURL = resourceHost;
app.mixin({
created() {
AOS.init({
duration: 500,
});
},
});
}
/**
* main.ts
*
* Bootstraps Vuetify and other plugins then mounts the App`
*/
// Components
import App from './App.vue';
// Composables
import { createApp } from 'vue';
// Plugins
import { registerPlugins } from '@/plugins';
const app = createApp(App);
registerPlugins(app);
app.mount('#app');
4. 사용하기
1. 먼저 templete 내에서는 {{ $t ('message.key값') }} 으로 사용할 수 있다.
<div>번역될 언어 ==> {{ $t('message.hello') }}</div>
2. script 내에서 사용하려면 i18n.global.t('message.key값') 으로 사용할 수 있다!
그리고 computed를 사용해서 반응성을 유지시켜주자!
import { i18n } from '@/plugins/index';
import { computed } from 'vue';
// 스크립트 내에서 사용하는 법
const mypages = computed(() => {
return [{ title: i18n.global.t('message.hello'), value: 1 }];
});
전체코드
<template>
<div style="padding-left: 50px">
<v-list :items="languages">
<v-list-item v-for="(lang, index) in languages" :key="index">
<v-btn color="primary" @click="switchLocale(lang.title)">
<v-list-item-title>{{ lang.title }}</v-list-item-title>
</v-btn>
</v-list-item>
</v-list>
<!-- 템플릿 내에서 사용하는 법 -->
<div>번역될 언어 ==> {{ $t('message.hello') }}</div>
<div>{{ mypages[0].title }}</div>
<div style="height: 50px"></div>
</div>
</template>
<script setup lang="ts">
import { i18n } from '@/plugins/index';
import { computed } from 'vue';
const languages = [
{ title: 'kr', value: 1 },
{ title: 'en', value: 2 },
{ title: 'jp', value: 3 },
];
// 스크립트 내에서 사용하는 법
const mypages = computed(() => {
return [{ title: i18n.global.t('message.hello'), value: 1 }];
});
const switchLocale = (lang) => {
if (i18n.global.locale.value === lang) return;
i18n.global.locale.value = lang;
};
</script>
# I18n 줄바꿈 하는 법
이스케이프 시퀀스(Escape Sequence)인 '\n' (Enter)을 사용하고,
css에서 root 혹은 *(전체 적용)에 white-space: pre-line을 적용시킨다!!
// appLocale.ts
export default {
messages: {
jp: {
message: {
hello: 'こんにちは\nこんにちは' // \n 줄바꿈을 원하는 곳에 넣어준다.
}
},
en: {
message: {
hello: 'h\ni'
}
},
kr: {
message: {
hello: '앙\n뇽'
}
},
}
}
/**
* src/styles/settings.scss
*
* Configures SASS variables and Vuetify overwrites
*/
// https://vuetifyjs.com/features/sass-variables/`
// @use 'vuetify/settings' with (
// $color-pack: false
// );
@import "./color.scss";
@import "./font.scss";
* {
white-space: pre-line ; // 적용!
font-family:'Pretendard','Helvetica Neue','Segoe UI','Apple SD Gothic Neo',sans-serif;
}
스크립트 내에서 사용하는 방법 아주 유용하쥬~ ㅎㅅㅎ
'Vue' 카테고리의 다른 글
[Vue3] watch 사용법(props 변경 감지하기) (0) | 2024.01.16 |
---|---|
[Vue3, Typescript] Uncaught TypeError: Cannot create property 'value' on number '0' (0) | 2024.01.11 |
[Vue3, Vuetify3, Typescript] Composition API를 사용하여 $refs를 통해 DOM 접근하기(ref 사용법) (2) | 2023.12.06 |
[Vue3] Composition API 전역 변수 파일 분리 (3) | 2023.11.28 |
[Vue3 + Vite] .env 환경변수를 찾을 수 없거나 사용할 수 없을 때! (0) | 2023.11.21 |