我想在我的Nuxt项目中设置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
},
],
}),
}发布于 2020-07-14 00:55:38
问题是,您给head提供了一个箭头函数,所以this不引用Nuxt实例,而是引用在nuxt.config.js中导出的Javascript对象。
您甚至可以通过将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
}
]
}
}
}https://stackoverflow.com/questions/62874848
复制相似问题