You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 3 vue-i18n内置修饰符如何在模板/代码中使用?

Vue 3 I18n 模板中使用修饰符的解决方案

Vue I18n 的内置修饰符默认仅支持在关联消息(即通过@引用其他消息的场景)中使用,你尝试的那些模板写法(比如$t("edit.capitalize"))之所以不生效,是因为修饰符并不是消息键的一部分,这种写法会被当成去查找名为edit.capitalize的消息,而非对edit应用修饰符。

下面是几种可行的解决方式:

方式一:扩展消息定义(利用内置修饰符机制)

直接在消息配置里新增一个带修饰符的关联项,把需要处理的消息通过@.修饰符:消息键的方式定义好,之后在模板里直接调用这个新的消息键即可:

// 国际化消息配置示例
messages: {
  en: {
    edit: 'edit',
    editCapitalized: '@.capitalize:edit', // 新增关联消息,应用首字母大写修饰符
    editDesc: '@.capitalize:edit description'
  }
}

模板中使用:

<button>{{ $t('editCapitalized') }}</button>

方式二:手动封装工具函数处理

如果不想新增消息键,可以自己写一个简单的工具函数,在模板里调用翻译后再处理文本格式。

全局过滤器方式(适用于选项式API)

在项目入口文件(比如main.js)注册全局过滤器:

import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
import App from './App.vue'

const i18n = createI18n({
  locale: 'en',
  messages: {
    en: { edit: 'edit' }
  }
})

const app = createApp(App)
// 注册全局首字母大写过滤器
app.config.globalProperties.$filters = {
  capitalize(str) {
    if (!str) return ''
    return str.charAt(0).toUpperCase() + str.slice(1)
  }
}

app.use(i18n).mount('#app')

模板中使用:

<button>{{ $filters.capitalize($t('edit')) }}</button>

组件内方法方式(适用于组合式API)

在组件里直接定义处理方法:

<script setup>
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

// 定义首字母大写方法
const capitalize = (str) => {
  if (!str) return ''
  return str.charAt(0).toUpperCase() + str.slice(1)
}
</script>

<template>
  <button>{{ capitalize(t('edit')) }}</button>
</template>

方式三:封装带修饰符的翻译函数(灵活扩展多种修饰符)

如果需要同时支持多种修饰符(比如大写、小写、首字母大写),可以封装一个自定义的翻译函数:

<script setup>
import { useI18n } from 'vue-i18n'
const { locale, messages } = useI18n()

const tWithModifiers = (key, modifiers = []) => {
  // 获取原始翻译文本
  let text = messages.value[locale.value][key] || key
  
  // 依次应用修饰符
  modifiers.forEach(mod => {
    switch(mod) {
      case 'capitalize':
        text = text.charAt(0).toUpperCase() + text.slice(1)
        break
      case 'uppercase':
        text = text.toUpperCase()
        break
      case 'lowercase':
        text = text.toLowerCase()
        break
      // 可根据需求扩展更多修饰符逻辑
    }
  })
  
  return text
}
</script>

<template>
  <button>{{ tWithModifiers('edit', ['capitalize']) }}</button>
  <!-- 示例:同时应用大写修饰符 -->
  <button>{{ tWithModifiers('edit', ['uppercase']) }}</button>
</template>

内容的提问来源于stack exchange,提问作者TheDoctor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 10:33:20