Thursday, 25 February 2021

Cannot read property '$options' of undefined making external js file for head options

I need to set up global head in Nuxt for my app, which some subpages will overwrite. Those global head needs to contain translated data.

I created seoHead.js file with code:

import Vue from "vue";

export const $t = (sign) => Vue.prototype.$nuxt.$options.i18n.t(sign);

export default {
  title: $t("seoGlobal.title"),
  meta: [
    { charset: "utf-8" },
    { name: "viewport", content: "width=device-width, initial-scale=1" },
    {
      hid: "description",
      name: "description",
      content: $t("seoGlobal.description"),
    },
    {
      hid: "ogSiteName",
      name: "og:site_name",
      content: "Test Page",
    },
    {
      hid: "ogTitle",
      name: "og:title",
      content: $t("seoGlobal.ogTitle"),
    },
    (...)
  ],
};

I import and use this data in my index.vue and other pages like this:

import seoHead from "~/constants/seoHead";

export default {
  head() {
    const metaI18n = this.$nuxtI18nSeo();
    const currentPath = process.env.LP_URL + this.$router.currentRoute.fullPath;
    return {
      ...seoHead,
      meta: [
        {
          hid: "ogLocale",
          name: "og:locale",
          content: metaI18n.meta[0].content,
        },
        {
          hid: "ogLocaleAlternate",
          name: "og:locale:alternate",
          content: metaI18n.meta[1].content,
        },
        {
          hid: "ogUrl",
          name: "og:url",
          content: currentPath,
        },
      ],
    };
  },
(...)

Unfortunately, I am facing Cannot read property '$options' of undefined error. It's strange for me, because I already used export const $t = (sign) => Vue.prototype.$nuxt.$options.i18n.t(sign); code in another js file. Anyone know why this error appears? You know the best way to translate global head options?



from Cannot read property '$options' of undefined making external js file for head options

No comments:

Post a Comment