使用文件
nuxt.config.js
文件,可以自定义 head
内容以添加一些元数据或其他内容:
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'awesome title',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
...
}
但是我在文档中找不到任何可以在
html
元素上设置属性的内容——我想设置 lang
属性。有办法做到吗?
来源:在 HTML 标签中声明语言·问题#388·nuxt/nuxt.js
head
支持 htmlAttrs
属性。它将把对象的每个key:value映射为attribute:value
module.exports = {
head: {
htmlAttrs: {
lang: 'en'
}
}
}
使用i18n时如何做到这一点:使用i18n和Nuxt时设置语言属性?
在 Nuxt 3 中输入组件
<script setup>
useHead({
htmlAttrs: {
lang: 'en',
style: 'font-size: 13px'
}
})
</script>
将 htmlAttrs 添加到
nuxt.config.js
export default defineNuxtConfig({
app: {
head: {
htmlAttrs: {
lang: 'en',
},
title: 'title',
charset: 'utf-8',
meta: [],
link: [],
}
},
})
对于 Nuxt 3 及更高版本,我建议使用以下方法,即使用
useHead()
内置可组合项(请参阅文档)。
这是一个示例
app.vue
文件(这是 Nuxt 用于渲染 SPA 的根组件)。
<template>
<main>
<NuxtPage />
</main>
</template>
<script setup lang="ts">
useHead({
htmlAttrs: {
lang: "en",
},
});
</script>
这样,您的代码将不会臃肿,因为
nuxt.config.ts
文件中引入的配置较少,并且还按照之前的旧答案中的建议对其进行了破解。