Home > Net >  How to use vue i18n $t in vuex getters in vue 3?
How to use vue i18n $t in vuex getters in vue 3?

Time:07-13

I want to use i18n $t in my getters for a static label. How can I do that?

I've tried importing like this:

import { i18n } from '../../locales/i18n.js';

const getters = {
    guaranteePolicies: state => {
        let guaranteesState = state.rangeUpdateData.guarantees;
        let guarantees = [{
            value : "",
            label :  i18n.t("chooseGuarantee"),
            disabled : true
        }];
        for (let index in guaranteesState) {
            guarantees.push({
                value : guaranteesState[index].ID,
                label : guaranteesState[index].Name
            });
        }
        return guarantees;
    }
}

but it gives me the error Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 't')

Thanks in advance :)

CodePudding user response:

As mentioned in i18n documentation here you can do it like this:

<script>
import { defineComponent } from 'vue'
import { useI18n } from 'vue-i18n'

export default defineComponent({
  name: 'Hello',
  setup() {
    const { t } = useI18n() // use as global scope
    return { t }
  }
})
</script>

<template>
  <p>{{ $t('hello') }}</p>
  <p>{{ t('hello') }}</p>
</template>

You can also use it in your getters as you use it in the template.

CodePudding user response:

Figure it out how to use it!

Instead of importing i18n with curly brackets, I'm importing like this:

import i18n from '../../locales/i18n.js'

and for accessing the $t function, I'm using

        label : i18n.global.t("chooseGuarantee")

and it's working perfectly! hope this helps someone :)

  • Related