AmirrezaJM
AmirrezaJM

Reputation: 158

How to dynamic dir and locale in HtmlAttr in Nuxt3?

I'm using @nuxtjs/i18n plugin with nuxt 3 and after I install it I wrote my i18n(config) in the nuxt.config.ts my code:

  i18n: {
    locales: [
        {
            code: 'fa',
            iso: 'fa-IR',
            name: 'Farsi',
            file: 'fa-IR.json',
            dir: 'rtl',
        },
        {
            code: 'en',
            iso: 'en-US',
            name: 'English',
            file: 'en-US.json',
            dir: 'ltr',
        },
    ],
    defaultLocale: 'fa',
    detectBrowserLanguage: false,
    langDir: "lang",
    vueI18n: {
        legacy: false,
        fallbackLocale: 'fa',
    }
}

after that, I use useLocaleHead({}) and useHead({}) in the default.vue(it's in my layout actually)

<script setup lang="ts">

const head = useLocaleHead({
  addDirAttribute: true,
  addSeoAttributes: true
});
useHead({
 htmlAttrs: {
   lang: head.value.htmlAttrs!.lang,
   dir: head.value.htmlAttrs!.dir
 },
});
</script>

but, when I run the project the dir and locale won't dynamic and change if I select another language. the output images: enter image description here enter image description here

as you can see dir and lang attributes on html tag won't change. however, the content's shown as english.
can anyone help how I can develop it with nuxt3??

Upvotes: 4

Views: 2562

Answers (3)

Putra Fajar Hasanuddin
Putra Fajar Hasanuddin

Reputation: 1193

U need to make it reactive

<script setup lang="ts">

const head = useLocaleHead({
  addDirAttribute: true,
  addSeoAttributes: true
});
useHead({
 htmlAttrs: {
   lang: () => head.value.htmlAttrs!.lang,
   dir: () => head.value.htmlAttrs!.dir
 },
});
</script>

Upvotes: 0

Hadi Majidi
Hadi Majidi

Reputation: 431

The short answer is just to add an html tag to your layouts/default file

<template>
   <Html :lang="head.htmlAttrs.lang" :dir="head.htmlAttrs.dir">
    ... the rest of your code in layouts/default
  </Html>
</template>

<script setup>
const head = useLocaleHead({
  addDirAttribute: true,
  identifierAttribute: 'id',
  addSeoAttributes: true
})
</script>

Upvotes: 1

Ali Azimi
Ali Azimi

Reputation: 404

I had the same problem and I solved it using <Html> tag in my layout file:

This is the content of my layouts\default.vue file

<template>
  <div>
    <Html :lang="head.htmlAttrs.lang" :dir="head.htmlAttrs.dir"></Html>
    <Navbar />
    <div class="content">
      <slot />
    </div>
  </div>
</template>

<script setup>
const head = useLocaleHead({
  addDirAttribute: true,
  identifierAttribute: 'id',
  addSeoAttributes: true
})
</script>

I hope it solved your problem

Upvotes: 4

Related Questions