首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >访问当前`$route.path`在nuxt.config.js中

访问当前`$route.path`在nuxt.config.js中
EN

Stack Overflow用户
提问于 2020-07-13 11:26:06
回答 1查看 2.7K关注 0票数 2

我想在我的Nuxt项目中设置og:url。我试图在nuxt.config.js文件中这样做,但是我似乎无法访问this.$route.path。这是我下面的代码。

nuxt.config.js

代码语言:javascript
复制
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
      },
    ],
  }),
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-14 00:55:38

问题是,您给head提供了一个箭头函数,所以this不引用Nuxt实例,而是引用在nuxt.config.js中导出的Javascript对象。

您甚至可以通过将this.$route.path调用替换为this.mode来看到这一点。您将看到universal被附加到内容中。

无论如何,要修复它,只需将箭头函数替换为一个普通函数,然后它将允许您使用this访问Nuxt上下文。

代码语言:javascript
复制
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
                }
            ]
        }
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62874848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档