快速開始
Vue
本頁示範 Intor 在 Vue 專案中的最小整合流程。
安裝
在此範例中,我們使用 Vite 來建立 Vue 專案,詳見:Vite
安裝 Intor:
npm install intoryarn add intorpnpm add intorbun add intor
專案結構
index.jsonUindex.jsonUApp.vueMHelloWorld.vueMintor-config.tsUintor-client-provider.vueU
整合步驟
♯1 翻譯內容
在專案中建立 messages 資料夾,並依語系建立子資料夾,每個語系提供一個 index.json。
index.jsonUindex.jsonU
{ "hello": "Hello, {name}", "rich": "A <tag>text</tag>." }
{ "hello": "Bonjour, {name}", "rich": "Un <tag>texte</tag>." }
♯2 設定檔
在 src/ 下建立 i18n/ 資料夾,並於其中建立 intor-config.ts。
本範例採用最基本的翻譯內容載入方式,直接將 messages 定義於設定檔中。
詳見:載入翻譯內容
intor-config.tsU
import { defineIntorConfig } from "intor"; import EN from "../../messages/en/index.json"; import FR from "../../messages/fr/index.json"; export const intorConfig = defineIntorConfig({ defaultLocale: "en", supportedLocales: ["en", "fr"], messages: { en: EN, fr: FR, }, });
♯3 初始化
在 i18n/ 資料夾中建立 intor-client-provider.vue。
intor-client-provider.vueU
<script setup lang="ts"> import { getClientLocale } from "intor"; import { IntorProvider } from "intor/vue"; import { intorConfig } from "./intor-config"; const locale = getClientLocale(intorConfig); </script> <template> <IntorProvider :value="{ config: intorConfig, locale }"> <slot /> </IntorProvider> </template>
接著,在 App.vue 中使用此 provider 作為應用程式的最外層包裝。
App.vueM
<script setup lang="ts"> import HelloWorld from "./components/HelloWorld.vue"; import IntorClientProvider from "./i18n/intor-client-provider.vue"; </script> <template> <IntorClientProvider> <HelloWorld /> </IntorClientProvider> </template>
使用範例
透過 useTranslator 取得翻譯相關能力:
t:取得對應文字setLocale:切換當前語系
<Trans />:渲染包含語意 tag 的結構化翻譯內容
HelloWorld.vueM
<script setup lang="ts"> import { Trans, useTranslator } from "intor/vue"; import { h } from "vue"; const { t, setLocale } = useTranslator(); </script> <template> <p>{{ t("hello", { name: "Intor" }) }}</p> <button @click="setLocale('en')">English</button> <button @click="setLocale('fr')">French</button> <Trans :i18n-key="'rich'" :components="{ tag: (children) => h('b', null, children) }" /> </template>