最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

nuxt.js - $t - global i18n function does not work in nuxt composables - Stack Overflow

programmeradmin0浏览0评论

so i have this in my nuxt.config

 i18n: {
    lazy: true,
    langDir: '../locales',
    locales: getLocales(),
    defaultLocale: 'en',
    strategy: 'no_prefix',
    experimental: {
      autoImportTranslationFunctions: true,
    },
  },

and "nuxt": "^3.15.0",

Throughout my app, I can use $t() for localization without issues.
When I try to use it inside a composable, I get an error saying $t is not defined.

At the same time, const { t } = useI18n() works inside the composable.

Why is $t not available in composables, and is there a way to make it work?

so i have this in my nuxt.config

 i18n: {
    lazy: true,
    langDir: '../locales',
    locales: getLocales(),
    defaultLocale: 'en',
    strategy: 'no_prefix',
    experimental: {
      autoImportTranslationFunctions: true,
    },
  },

and "nuxt": "^3.15.0",

Throughout my app, I can use $t() for localization without issues.
When I try to use it inside a composable, I get an error saying $t is not defined.

At the same time, const { t } = useI18n() works inside the composable.

Why is $t not available in composables, and is there a way to make it work?

Share Improve this question asked Mar 4 at 12:48 Павел ХорольськийПавел Хорольський 555 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You need to useI18n() inside your composable, as the $i18n instance is not available inside composables.
Actually, inside composables, you may not call composables (see code:)

// useExample.ts
// Not OK
export function useExample() {
    const coolFeature = useCoolFeature();

    function myExampleFn() {
        coolFeature()
    }
    
    return {
        myExampleFn
    }
}

// OK
export function useExample() {
    function myExampleFn() {
        const coolFeature = useCoolFeature();
        coolFeature()
    }
    
    return {
        myExampleFn
    }
}

// In your case
export function useExample() {
    function myExampleFn() {
        const i18n = useI18n();
        return i18n.t('Peace')
    }
    
    return {
        myExampleFn
    }
}

// Other approach would be, to inject the functionality needed into the composable.
// This approach may be the fastest, see dependency injection as a pattern
发布评论

评论列表(0)

  1. 暂无评论