Cas*_*Cas 5 html vue.js nuxt.js
我有一个用 Nuxt 构建的网页,对于不同的页面,我希望在头部有不同的标题和不同的元描述。我该怎么做呢?
我在 Nuxt 文档中找到了 head() 方法,但这似乎对我不起作用。
在我的 contact.vue 中:
export default class Contact extends Vue {
head() {
return {
title: 'Contact page',
meta: [
{ hid: 'description', name: 'description', content: 'This is a contact page' }
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的 nuxt.config.js 中:
head: {
title: 'My website',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
],
}
Run Code Online (Sandbox Code Playgroud)
根据文档,我希望这能生成元标记。但它只显示 nuxt.config.js 中声明的标题和元描述。我在这里缺少什么?
我想到了。在组件中,我将 head 方法放在类中。这不起作用。当我将它放入组件装饰器中时,如下所示:
@Component({
head(): object {
return {
title: this.$i18n.t('meta.home.title'),
meta: [
{
hid: 'description',
name: 'description',
content: this.$i18n.t('meta.home.description')
},
]
}
}
})
export default class Home extends Vue {
...
}
Run Code Online (Sandbox Code Playgroud)
它确实有效。
一开始我遇到了一个错误
Object literal may only specify known objects and 'head' does not exist in type 'ComponentOptions'
Run Code Online (Sandbox Code Playgroud)
这是通过扩展 ComponentOptions 来解决的,如下所示:
declare module "vue/types/options" {
interface ComponentOptions<V extends Vue> {
head?: etc etc
}
}
Run Code Online (Sandbox Code Playgroud)