# vue: useMessages URL: https://generaltranslation.com/zh/docs/vue/reference/composables/use-messages.mdx --- title: useMessages description: 将通过 msg 注册的字符串解析为当前区域设置对应的内容。useMessages API 参考。 --- `useMessages` composable 会返回一个同步解析器,用于解析通过 [`msg()`](/docs/vue/reference/functions/msg) 注册的字符串。它也接受普通源字符串,并保留空值。 ## 概述 [#overview] 在模块作用域中注册源文本,然后在组件内解析每个已注册的字符串: ```ts title="src/messages.ts" import { msg } from 'gt-vue'; export const savedMessage = msg('Your preferences are saved.', { $context: 'Settings confirmation', }); ``` ```vue title="SettingsStatus.vue" ``` ## 工作原理 [#how-it-works] * **已注册消息。** [`msg()`](/docs/vue/reference/functions/msg) 注册源文本以供提取。传入 options 时,它会编码源文本和上下文元数据,且这些元数据优先于调用处的 options;未传入 options 时,则原样返回源字符串。 * **原始字符串。** 普通字符串会像通过 [`useGT()`](/docs/vue/reference/composables/use-gt) 调用一样进行查找,并可提供调用处的 `$context`。 * **空值透传。** `null` 返回 `null`,`undefined` 返回 `undefined`。 * **源文本后备。** catalog 条目缺失或不兼容时,返回原始源字符串。 * **仅限普通字符串。** 花括号保持字面含义;不会执行 ICU 格式化或插值。 如果解析器应随 [`createGT()`](/docs/vue/reference/functions/create-gt) 的 catalog 或区域设置变化而更新,请在模板、`computed` 或其他响应式 effect 中调用它。在 setup 期间仅解析一次的值是普通字符串快照。通过 [`initializeGTSPA()`](/docs/vue/reference/functions/initialize-gt-spa) 初始化的 browser SPA 会预加载初始 catalog,并在区域设置变更后重新加载时重建快照。 ## 参数 [#parameters] `useMessages` 不接收任何参数。 ## 返回值 [#returns] **类型** `(message: T, options?: GTStringOptions) => T extends string ? string : T` 一个同步解析器,接受以下参数: | 参数 | 描述 | 类型 | 可选 | 默认值 | | --------------------- | ----------------- | ---------------------------------------------------------------- | -- | ---- | | [`message`](#message) | 已注册的消息、原始源字符串或空值。 | `string \| null \| undefined` | 否 | — | | [`options`](#options) | 未编码的原始源字符串的上下文。 | [`GTStringOptions`](/docs/vue/reference/types/gt-string-options) | 是 | `{}` | ### `message` **类型** `string | null | undefined` · **必填** 由 [`msg()`](/docs/vue/reference/functions/msg) 返回的单个字符串、静态原始源字符串、`null` 或 `undefined`。如果 [`msg()`](/docs/vue/reference/functions/msg) 注册的是数组,则分别解析其中的每个成员。 ### `options` **类型** [`GTStringOptions`](/docs/vue/reference/types/gt-string-options) · **可选** · **默认值** `{}` 唯一支持的字段为 `$context?: string`,适用于原始源字符串。由 [`msg()`](/docs/vue/reference/functions/msg) 编码的上下文具有更高优先级。 ## 示例 [#examples] 无需单独进行守卫检查即可解析可为空的已注册消息: ```vue title="StatusMessage.vue" ``` 结合上下文解析原始字符串: ```vue

{{ m('Open', { $context: 'Adjective: an open issue' }) }}

```