How to change the link and href attributes of the link tag dynamically after changing the language in the nuxt 3 application

36 Views Asked by At

How to change page metadate when changing language.

On stackoverflow

How to dynamic dir and locale in HtmlAttr in Nuxt3?

There is a method that changes the lang and dir attributes of an html tag.

However, I need to change the rel and href attributes of the link tag in the head section.

This must be done dynamically when the language changes. If we go along the localized path, the localized values will be substituted in the useHead composite. However, if we change the language, the values ​​from the previous locale will remain.

I tried the following methods.

Create a hook that is called when the language is changed, which in turn calls useHead. However, this is not a working method.

<script setup lang="ts">
const { t } = useI18n();

useHead({
  // TODO: словить изменение языка и поставить нужны рефланги
  link: [{ rel: t("myLocaleRefValue"), href: t("myLocaleHrefValue") }],
});

const { setLocale } = useI18n();
async function useLocaleHook(locale:string) {
  await setLocale(locale)
  useHead({
    link: [{ rel: t("myLocaleRefValue"), href: t("myLocaleHrefValue") }],
  });
}
</script>

<template>
  <Body>
    <NuxtLayout>
      <NuxtLoadingIndicator />
      <NuxtPage />
    </NuxtLayout>
  </Body>
</template>
1

There are 1 best solutions below

0
Andrey Frolov On

Hurray, I found a solution.

To do this, instead of just passing a value, you need to wrap it in an arrow function and then the values will be substituted reactively.

useHead({
  link: [{ rel: () => t("myLocaleRelValue"), href: () => t("myLocaleHrefValue"), }],
});

This way the values will be substituted reactively.