我想在我的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
},
],
}),
}
答案 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
}
]
}
}
}