在nuxt.config.js内部访问当前的`$ route.path`

时间:2020-07-13 11:26:06

标签: nuxt.js

我想在我的Nuxt SSR项目中设置og:url。我正在尝试在nuxt.config.js文件中执行此操作,但是似乎无法访问this.$route.path。这是我下面的当前代码。

nuxt.config.js

require('dotenv').config()

export default {
  mode: 'universal',
  target: 'static',

  generate: {
    fallback: true
  },

  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:3000'
  },

  head: () => ({
    meta: [
      {
        hid: 'og:url',
        name: 'og:url',
        content: process.env.baseUrl + this.$route.path
      },
    ],
  }),
}

1 个答案:

答案 0 :(得分:1)

您几乎拥有它,问题在于您要向head提供箭头功能,因此this不是指Nuxt实例,而是指您要导出的Javascript对象在nuxt.config.js中。

您甚至可以通过将this.$route.path调用替换为this.mode来看到此操作。您会看到universal被附加到您的内容中。

无论如何,要解决该问题,只需将箭头功能替换为普通功能,然后即可使用this访问Nuxt上下文:

require('dotenv').config()

export default {
    mode: 'universal',
    target: 'static',

    generate: {
        fallback: true
    },

    env: {
        baseUrl: process.env.BASE_URL || 'http://localhost:3000'
    },

    head() {
        // this.$route is undefined when generating the fallback page
        const path = this.$route ? process.env.baseUrl + this.$route.path : process.env.baseUrl
        return {
            meta: [
                {
                    hid: 'og:url',
                    name: 'og:url',
                    content: path
                }
            ]
        }
    }
}