如何在Nuxt中为HTML元素设置lang属性?
lang attribute on the HTML element in Nuxt.js? Question
I know we can customize page head content and add metadata via the nuxt.config.js file, like this example:
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' } ] }, ... }
But I couldn't find any documentation on setting attributes for the HTML element. Is there a way to set the lang attribute for the HTML tag?
Answer
Great question! You absolutely can set the lang attribute on the root HTML element in Nuxt.js, and it’s simpler than you might think. The head object in your nuxt.config.js supports an htmlAttrs property specifically for adding attributes to the <html> tag.
Here’s how to implement it:
- Inside the
headconfiguration block, add anhtmlAttrsobject. - Within that object, define the
langkey with your target language code (e.g.,'en'for English,'es'for Spanish).
Static Language Example
module.exports = { head: { title: 'awesome title', // Add this section to set static lang attribute htmlAttrs: { lang: 'en' }, 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' } ] }, // ... other Nuxt config options }
This will render your HTML root tag like this:
<html lang="en"> <!-- Your page content here --> </html>
If you’re working on a multilingual site and need dynamic language switching, you can also define htmlAttrs as a function in your layouts or page components. This lets you access the app context to pull the current locale (for example, if you’re using Nuxt’s i18n module):
Dynamic Language Example
// In your default layout file (layouts/default.vue) export default { head({ app }) { return { htmlAttrs: { lang: app.i18n.locale } } } }
This way, the lang attribute will update automatically whenever the user switches languages on your site.
内容的提问来源于stack exchange,提问作者rocambille

