一直都说Nuxt对SEO友好。这是因为,Nuxt提供强大的head配置工具,使得搜索引擎在检索到页面之后,会读取准确的,丰富的Head,提高SEO效果。
默认
Nuxt提供开箱即用的默认配置,但是你可以进行覆盖
在nuxt.config.ts
中配置全局的head
export default defineNuxtConfig({
app: {
head: {
charset: 'utf-8',
viewport: 'width=device-width, initial-scale=1',
}
}
})
useHead
useHead
在vue文件中,动态编程的定义一个head。
仅仅可以在setup
中或者是生命周期hooks中使用
<script setup lang="ts">
useHead({
title: 'My App',
meta: [
{ name: 'description', content: 'My amazing site.' }
],
bodyAttrs: {
class: 'test'
},
script: [ { innerHTML: 'console.log(\'Hello world\')' } ]
})
</script>
useSeoMeta
使用这个函数可以定义SEO meta 标签
<script setup lang="ts">
useSeoMeta
({
title: 'My Amazing Site',
ogTitle: 'My Amazing Site',
description: 'This is my amazing site, let me tell you all about it.',
ogDescription: 'This is my amazing site, let me tell you all about it.',
ogImage: 'https://example.com/image.png',
twitterCard: 'summary_large_image',
})
</script>
SEO相关的组件
Nuxt提供 <Title>
, <Base>
, <NoScript>
, <Style>
, <Meta>
, <Link>
, <Body>
, <Html>
和 <Head>
组件,以便您可以直接与组件模板中的元数据进行交互
<script setup lang="ts">
const title = ref('Hello World')
</script>
<template>
<div>
<Head>
<Title>{{ title }}</Title>
<Meta name="description" :content="title" />
<Style type="text/css" children="body { background-color: green; }" ></Style>
</Head>
<h1>{{ title }}</h1>
</div>
</template>
mate的类型
以下是useHead和app.head或者是SEO组件可以使用的非响应式类型
interface MetaObject {
title?: string
titleTemplate?: string | ((title?: string) => string)
templateParams?: Record<string, string | Record<string, string>>
base?: Base
link?: Link[]
meta?: Meta[]
style?: Style[]
script?: Script[]
noscript?: Noscript[];
htmlAttrs?: HtmlAttributes;
bodyAttrs?: BodyAttributes;
}
功能
响应式支持
<script setup lang="ts">
const description = ref('My amazing site.')
useHead({
meta: [
{ name: 'description', content: description }
],
})
</script>
title template
如果你的标题有特定的格式,你可以使用以下的方式
<script setup lang="ts">
useHead({
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title';
}
})
</script>
body tags
你可以使用tagPostition:'bodyClose'
使得标签添加到body的末尾。
例如在body标签的末尾引入一个第三方的js脚本
<script setup lang="ts">
useHead({
script: [
{
src: 'https://third-party-script.com',
// valid options are: 'head' | 'bodyClose' | 'bodyOpen'
tagPosition: 'bodyClose'
}
]
})
</script>
官方还有一些例子
- 动态标题
- 拓展的css