ドキュメンテーション

Vue

Vue アプリで Magic Translate を使う方法。Vue クライアントは Vue 3.3 以降が必要で、Nuxt でも動作する。

設置

Magic Translate の Vue クライアントをアプリにインストールする。

# using npm
npm i @magic-translate/vue
# using yarn
yarn add @magic-translate/vue

次に、プラグインをアプリにインストールする。

// main.ts
import { createApp } from 'vue';
import { createMagicTranslate, Language } from '@magic-translate/vue';
import App from './App.vue';
createApp(App)
.use(
createMagicTranslate({
apiKey: '<your-api-key>',
language: Language.DE // any supported language
})
)
.mount('#app');

APIキーをまだ持っていないなら、Magic Translate にサインアップして取得しよう。

これで、<T> コンポーネントはどのテンプレートでも使用できる。プラグインはそれをグローバルに登録する。

<template>
<h1><T>Please translate me!</T></h1>
</template>

それだ。あなたのアプリは今70以上の言語に翻訳できる。

構成

createMagicTranslate は次のオプションを受け入れる:

オプション説明
apiKey必須。あなたの Magic Translate APIキー。
language必須。コンテンツが翻訳された言語、例えば 'de'。
sourceLanguageテンプレートが書かれている言語。自動的に検出されるので、検出結果が間違っている場合にのみ設定して。
formality'formal' または 'informal'。すべての言語でサポートされているわけではない。翻訳ごとに上書きできる。
debugリクエストをコンソールに記録する。

言語を変える

useLanguageSwitcher は現在の言語を読み込んで変更する。すべての <T> コンポーネントと t 関数は自動的に更新される。

<script setup lang="ts">
import { useLanguageSwitcher } from '@magic-translate/vue';
const { currentLanguage, setLanguage } = useLanguageSwitcher();
</script>
<template>
<div>Current language is: {{ currentLanguage }}</div>
<button @click="setLanguage('de')">German</button>
</template>

currentLanguage は読み取り専用の参照なので、computed と watch でも使える。

Nuxt

Magic Translate と Nuxt を使うには、プラグインファイルに登録して:

// plugins/magic-translate.ts
import { createMagicTranslate } from '@magic-translate/vue';
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(
createMagicTranslate({
apiKey: useRuntimeConfig().public.magicTranslateApiKey,
language: 'de'
})
);
});

<T> コンポーネントと t 関数はブラウザで翻訳される。サーバー側のレンダリングでは、サーバーが元のコンテンツをレンダリングし、ハイドレーション後に翻訳される。

サンプルプロジェクト

GitHubでサンプルプロジェクトを見つけて、ライブで見ることができる。