搜尋

首頁  >  問答  >  主體

Vue 3 vue-i18n。如何在應用程式(.vue 檔案)之外使用 $t(t)?合成API

<p>我想在元件外部格式化我的日期時間。 </p> <pre class="brush:js;toolbar:false;">function transformDatetime(config, value) { if (value) { return $d(new Date(value), config); } return $t('-'); } </pre> <p>我正在嘗試從應用程式實例獲取 $t。但它只在元件上下文中起作用,就像 useI18n 一樣。 </p> <pre class="brush:js;toolbar:false;">import { getCurrentInstance } from 'vue' export default function useGlobal() { const instance = getCurrentInstance() if (!instance) return return instance.appContext.config.globalProperties } </pre> <p><br /></p>
P粉032649413P粉032649413541 天前492

全部回覆(1)我來回復

  • P粉143640496

    P粉1436404962023-08-27 00:25:26

    我找到了解決方案。只需將您的 i18n 匯入到應用程式外部的檔案中,然後使用 i18n.global.t

    import { createI18n } from "vue-i18n"
    
    export const i18n = createI18n({
        legacy: false,
        locale: 'ja',
        fallbackLocale: 'en',
        messages,
    })
    
    import { i18n } from '@/i18n'
    
    const { t: $t, d: $d, n: $n } = i18n.global
    
    const expample = $t('some-text')
    

    回覆
    0
  • 取消回覆