vue.jsnuxt.jsnuxt3.jsvue-i18nnuxt-i18n

How to watch for i18n locale change in Nuxt?


I've installed nuxt 3 and i18n

I want to change document direction when locale switched

for example <body dir="ltr"> to <body dir="rtl" >

But I couldn't find any callback function for that in the document !

i know I can put some watch on $i18n.locale But I think it's not best way to do that .

I remember in Nuxt 2 / i18n we had a callback named "onLocaleChanged" but I couldn't find that in new version !

plugins/i18n.ts

import { createI18n } from 'vue-i18n'
import en from '~~/locales/en'
import fa from '~~/locales/fa'
export default defineNuxtPlugin(({ vueApp }) => {
  const i18n = createI18n({
    legacy: false,
    globalInjection: true,
    locale: 'fa',
    messages: {
      en,fa
    }
  })
  vueApp.use(i18n)
})

package.json

{
  "private": true,
  "scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev",
    "generate": "nuxt generate",
    "preview": "nuxt preview",
    "postinstall": "nuxt prepare"
  },
  "devDependencies": {
    "@intlify/unplugin-vue-i18n": "^0.7.0",
    "@intlify/vite-plugin-vue-i18n": "^6.0.3",
    "@nuxtjs/tailwindcss": "^5.3.3",
    "nuxt": "3.0.0-rc.10",
    "sass": "^1.55.0",
    "sass-loader": "10.1.1",
    "tailwindcss-flip": "^1.0.0",
    "vue-i18n": "^9.2.2"
  },
  "dependencies": {
    "@heroicons/vue": "^2.0.11",
    "@kyvg/vue3-notification": "^2.4.1",
    "@nuxt-hero-icons/outline": "^1.0.1",
    "@nuxt-hero-icons/solid": "^1.0.1",
    "@pinia/nuxt": "^0.4.2",
    "@vueform/multiselect": "^2.5.2",
    "axios": "^0.27.2",
    "daisyui": "^2.28.0",
    "jenesius-vue-modal": "^1.7.2",
    "sweetalert2": "^11.4.33",
    "vee-validate": "^4.6.7",
    "vue-recaptcha-v3": "^2.0.1",
    "vue3-loading-overlay": "^0.0.0",
    "yup": "^0.32.11"
  }
}

Solution

  • You could use something like this answer.

    watch: {
      '$i18n.locale': function(newVal, oldVal) {
        console.log('locale change', newVal)
      }
    }
    

    Since I'm not sure that there is a given event for this purpose.