I have a vue app using vue-i18n-routing (https://github.com/intlify/routing) which is based on @nuxtjs/i18n (https://i18n.nuxtjs.org). I have it running and it handles the routing and language switching beautifully, except from one problem I’m having:
I can’t access setLocale()
. Here’s the details on this from https://i18n.nuxtjs.org/docs/api/vue-i18n#setlocale:
setLocale()
Arguments:
locale (type: string)
Returns: Promise<void>
Switches locale of the app to specified locale code. If useCookie option is enabled, locale cookie will be updated with new value. If prefixes are enabled (strategy other than no_prefix), will navigate to new locale's route.
I need to use this so that the url changes to reflect the chosen locale. However, I don’t know what or how to import in order to actually use this feature. I’ve read the docs, looked at examples, and searched for similar questions, but nothing has helped me. I suspect I’m overlooking something basic.
Here’s my router config:
import { createRouter as _createRouter } from 'vue-i18n-routing'
import { createWebHistory } from 'vue-router'
import type { I18n } from 'vue-i18n'
export function createRouter(i18n: I18n) {
return _createRouter(i18n, {
version: 4,
detectBrowserLanguage: {
alwaysRedirect: false,
fallbackLocale: 'en',
redirectOn: 'no prefix',
},
strategy: 'prefix_and_default',
trailingSlash: true,
defaultLocale: 'en',
locales: [
{
code: 'en',
iso: 'en-US',
name: 'English'
},
{
code: 'fr',
iso: 'fr-FR',
name: 'French'
}
],
history: createWebHistory(import.meta.env.BASE_URL),
},
routes: [
/* not shown */
]
})
}
And where I create i18n:
import { createI18n } from 'vue-i18n'
import en from './locales/en.json'
import fr from './locales/fr.json'
const i18n = createI18n<true>({
legacy: true,
messages: {
en,
fr
}
})
export default i18n
And my language switcher with both a working and a non-working example:
<div v-if="$i18n.locale === 'en'">
<a @click="$i18n.locale = 'fr'">FR</a> // works, but lacks the url changing I need
</div>
<div v-if="$i18n.locale === 'fr'">
<a @click="$i18n.setLocale('en')">EN</a> // doesn't work at all (Property 'setLocale' may not exist on type 'VueI18n')
</div>
Can someone help me get this setLocale() feature working?