Home  >  Q&A  >  body text

Vue 3 vue-i18n. How to use $t(t) outside the application (.vue file)? Synthesis API

<p>I want to format my datetime outside the component. </p> <pre class="brush:js;toolbar:false;">function transformDatetime(config, value) { if (value) { return $d(new Date(value), config); } return $t('-'); } </pre> <p>I'm trying to get $t from the application instance. But it only works in component context, just like 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粉032649413419 days ago415

reply all(1)I'll reply

  • P粉143640496

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

    I found the solution. Just import your i18n into a file outside your application and use 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')
    

    reply
    0
  • Cancelreply