# Vue: t
URL: https://generaltranslation.com/zh/docs/vue/reference/functions/t.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 从已初始化的浏览器 SPA 运行时同步翻译普通字符串。t 的 API 参考。

在仅限浏览器的单页应用中，对于在 Vue 组件外求值的常量和其他字符串，请使用 `t`。组件代码通常应改用响应式的 [`useGT()`](/docs/vue/reference/composables/use-gt) 回调。

## 概览 [#overview]

```ts
const t: GTFunction;
```

该函数会读取由 [`initializeGTSPA()`](/docs/vue/reference/functions/initialize-gt-spa) 预加载的目录：

```ts title="src/navigation.ts"
import { t } from 'gt-vue';

export const navigation = [
  t('Documentation', { $context: 'primary navigation' }),
  t('Account settings'),
];
```

使用字面量源字符串和字面量 `$context`，以便 CLI 提取与运行时哈希对应的同一目录条目。

## 参数 [#parameters]

| 参数        | 说明                        | 类型                                                               | 可选 | 默认值  |
| --------- | ------------------------- | ---------------------------------------------------------------- | -- | ---- |
| `message` | 要翻译的静态源字符串。花括号按字面处理。      | `string`                                                         | 否  | —    |
| `options` | 用于消除 目录 hash 歧义的上下文。 | [`GTStringOptions`](/docs/vue/reference/types/gt-string-options) | 是  | `{}` |

`$context` 是唯一支持的选项。`t` 不接受插值变量、`$format`、`$maxChars` 或 `$requiresReview`。

## 工作原理 [#how-it-works]

`t` 根据 `message` 和 `$context` 计算纯 `STRING` 目录 hash，然后同步读取当前活动的 SPA 目录。如果找不到该 hash，或 目录 中的值不是字符串，则返回源字符串。

结果是调用执行时生成的翻译快照。模块级常量不会参与 Vue 的响应式系统。因此，SPA 区域设置变更会重新加载文档、重新运行 引导、预加载新的 目录，并重新评估模块。

此 API 仅执行字面字符串查找：

* `{name}` 等花括号内容只是普通字符。
* 不会解析或格式化 ICU 语法。
* 不会对运行时值进行插值。
* 不支持 `` t`Hello` `` 等标签模板语法。

对于包含运行时值的可翻译内容，请结合使用 [`<T>`](/docs/vue/reference/components/t) 和 [`<Var>`](/docs/vue/reference/components/var)。

## 返回值 [#returns]

**类型** `string`

返回匹配的字符串翻译；如果没有对应的字符串翻译，则返回 `message`。

## 失败 [#failures]

以下任一情况下，`t` 都会抛出错误：

* 它在服务器端运行，浏览器全局翻译状态可能会在不同请求之间泄漏。
* 它在浏览器中运行时，[`initializeGTSPA()`](/docs/vue/reference/functions/initialize-gt-spa) 尚未完成。

在引导模块中等待初始化器完成，然后动态导入调用 `t` 的模块。对于服务器端渲染，请创建请求作用域的 [`createGT({ locale })`](/docs/vue/reference/functions/create-gt#server-rendering) 状态，并在组件中通过 [`useGT()`](/docs/vue/reference/composables/use-gt) 进行翻译。

## 示例 [#example]

```ts title="src/status.ts"
import { t } from 'gt-vue';

export const STATUS_LABELS = {
  draft: t('Draft', { $context: 'document status' }),
  published: t('Published', { $context: 'document status' }),
};
```

提取器会注册这两个调用。当活动目录不可用，或其中不包含任一条目时，值分别为 `"Draft"` 和 `"Published"`。

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
