样式
Nuxt 在样式处理方面具有极高的灵活性。你可以编写自己的样式,或者引用本地和外部样式表。你可以使用 CSS 预处理器、CSS 框架、UI 库和 Nuxt 模块来为你的应用添加样式。
本地样式表
如果你正在编写本地样式表,最自然的地方是放在 app/assets/ 目录中。
在组件内部导入
你可以直接在页面、布局和组件中导入样式表。你可以使用 JavaScript 导入,或者使用 CSS @import 语句。
<script>
// Use a static import for server-side compatibility
import '~/assets/css/first.css'
// Caution: Dynamic imports are not server-side compatible
import('~/assets/css/first.css')
</script>
<style>
@import url("~/assets/css/second.css");
</style>
CSS 属性
你还可以在 Nuxt 配置中使用 css 属性。存放样式表的自然位置是 app/assets/ 目录。然后你可以引用它的路径,Nuxt 会将其包含在你应用的所有页面中。
export default defineNuxtConfig({
css: ['~/assets/css/main.css'],
})
使用字体
将你的本地字体文件放在 public/ 目录中,例如在 public/fonts 中。然后你可以在样式表中使用 url() 引用它们。
@font-face {
font-family: 'FarAwayGalaxy';
src: url('/fonts/FarAwayGalaxy.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap;
}
然后在你的样式表、页面或组件中通过名称引用你的字体
<style>
h1 {
font-family: 'FarAwayGalaxy', sans-serif;
}
</style>
通过 NPM 分发的样式表
你还可以引用通过 npm 分发的样式表。让我们以流行的 animate.css 库为例。
npm install animate.css
yarn add animate.css
pnpm install animate.css
bun install animate.css
deno install npm:animate.css
然后你可以在页面、布局和组件中直接引用它
<script>
import 'animate.css'
</script>
<style>
@import url("animate.css");
</style>
该包也可以作为字符串在 Nuxt 配置的 css 属性中引用。
export default defineNuxtConfig({
css: ['animate.css'],
})
外部样式表
你可以通过在 nuxt.config 文件的 head 部分添加 link 元素来将外部样式表包含在你的应用中。你可以使用不同的方法来实现这一点。请注意,本地样式表也可以通过这种方式包含。
你可以使用 Nuxt 配置的 app.head 属性来操作 head
export default defineNuxtConfig({
app: {
head: {
link: [{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css' }],
},
},
})
动态添加样式表
你可以在代码中使用 useHead 组合式函数来动态设置 head 中的值。
useHead({
link: [{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css' }],
})
Nuxt 底层使用 unhead,你可以参考 其完整文档。
使用 Nitro 插件修改渲染的 Head
如果你需要更高级的控制,你可以使用钩子(hook)拦截渲染的 HTML 并以编程方式修改 head。
在 ~~/server/plugins/my-plugin.ts 中创建一个插件,如下所示
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook('render:html', (html) => {
html.head.push('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">')
})
})
外部样式表是渲染阻塞资源:它们必须在浏览器渲染页面之前加载和处理。包含不必要的大型样式的网页需要更长的渲染时间。你可以在 web.dev 上阅读更多相关信息。
使用预处理器
要使用 SCSS、Sass、Less 或 Stylus 等预处理器,请先安装它。
npm install -D sass
npm install -D less
npm install -D stylus
编写样式表的自然位置是 app/assets 目录。然后你可以在你的 app.vue(或布局文件)中使用你的预处理器语法导入你的源文件。
<style lang="scss">
@use "~/assets/scss/main.scss";
</style>
或者,你可以使用 Nuxt 配置中的 css 属性。
export default defineNuxtConfig({
css: ['~/assets/scss/main.scss'],
})
如果你需要在预处理文件中注入代码,比如带有颜色变量的 Sass 片段,你可以通过 Vite 的 预处理器选项来实现。
在你的 app/assets 目录中创建一些片段文件
$primary: #49240F;
$secondary: #E4A79D;
$primary: #49240F
$secondary: #E4A79D
然后在你的 nuxt.config 中
export default defineNuxtConfig({
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: '@use "~/assets/_colors.scss" as *;',
},
},
},
},
})
export default defineNuxtConfig({
vite: {
css: {
preprocessorOptions: {
sass: {
additionalData: '@use "~/assets/_colors.sass" as *\n',
},
},
},
},
})
Nuxt 默认使用 Vite。如果你希望改用 webpack,请参考各预处理器加载器的文档。
预处理器工作线程 (实验性)
Vite 提供了一个实验性选项,可以加快预处理器的使用速度。
你可以在你的 nuxt.config 中启用它
export default defineNuxtConfig({
vite: {
css: {
preprocessorMaxWorkers: true, // number of CPUs minus 1
},
},
})
单文件组件 (SFC) 样式
Vue 和 SFC 最棒的特性之一是它们能够非常自然地处理样式。你可以直接在组件文件的 style 块中编写 CSS 或预处理器代码,从而获得极佳的开发体验,而无需使用 CSS-in-JS 之类的东西。但是,如果你希望使用 CSS-in-JS,你可以找到支持它的第三方库和模块,例如 pinceau。
你可以参考 Vue 文档以获取关于在 SFC 中为组件编写样式的全面参考。
Class 与 Style 绑定
你可以利用 Vue SFC 的特性,通过 class 和 style 属性来为组件设置样式。
<script setup lang="ts">
const isActive = ref(true)
const hasError = ref(false)
const classObject = reactive({
'active': true,
'text-danger': false,
})
</script>
<template>
<div
class="static"
:class="{ 'active': isActive, 'text-danger': hasError }"
/>
<div :class="classObject" />
</template>
<script setup lang="ts">
const isActive = ref(true)
const error = ref(null)
const classObject = computed(() => ({
'active': isActive.value && !error.value,
'text-danger': error.value && error.value.type === 'fatal',
}))
</script>
<template>
<div :class="classObject" />
</template>
<script setup lang="ts">
const isActive = ref(true)
const errorClass = ref('text-danger')
</script>
<template>
<div :class="[{ active: isActive }, errorClass]" />
</template>
<script setup lang="ts">
const activeColor = ref('red')
const fontSize = ref(30)
const styleObject = reactive({ color: 'red', fontSize: '13px' })
</script>
<template>
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }" />
<div :style="[baseStyles, overridingStyles]" />
<div :style="styleObject" />
</template>
有关更多信息,请参考 Vue 文档。
使用 v-bind 的动态样式
你可以使用 v-bind 函数在 style 块中引用 JavaScript 变量和表达式。这种绑定将是动态的,这意味着如果变量值发生变化,样式也将随之更新。
<script setup lang="ts">
const color = ref('red')
</script>
<template>
<div class="text">
hello
</div>
</template>
<style>
.text {
color: v-bind(color);
}
</style>
作用域样式
scoped 属性允许你隔离地为组件设置样式。使用此属性声明的样式将仅应用于当前组件。
<template>
<div class="example">
hi
</div>
</template>
<style scoped>
.example {
color: red;
}
</style>
CSS 模块
你可以通过 module 属性使用 CSS 模块。通过注入的 $style 变量进行访问。
<template>
<p :class="$style.red">
This should be red
</p>
</template>
<style module>
.red {
color: red;
}
</style>
预处理器支持
SFC style 块支持预处理器语法。Vite 内置支持 .scss、.sass、.less、.styl 和 .stylus 文件,无需配置。你只需要先安装它们,然后就可以在 SFC 中通过 lang 属性直接使用。
<style lang="scss">
/* Write scss here */
</style>
<style lang="sass">
/* Write sass here */
</style>
<style lang="less">
/* Write less here */
</style>
<style lang="stylus">
/* Write stylus here */
</style>
你可以参考 Vite CSS 文档和 @vitejs/plugin-vue 文档。对于 webpack 用户,请参考 vue loader 文档。
使用 PostCSS
Nuxt 内置了 postcss。你可以在 nuxt.config 文件中对其进行配置。
export default defineNuxtConfig({
postcss: {
plugins: {
'postcss-nested': {},
'postcss-custom-media': {},
},
},
})
为了在 SFC 中获得正确的语法高亮,你可以使用 postcss lang 属性。
<style lang="postcss">
/* Write postcss here */
</style>
默认情况下,Nuxt 已预先配置了以下插件
- postcss-import:改进
@import规则 - postcss-url:转换
url()语句 - autoprefixer:自动添加厂商前缀
- cssnano:压缩和清理
利用布局实现多种样式
如果你需要让应用的各个部分拥有完全不同的样式,你可以使用布局。为不同的布局使用不同的样式。
<template>
<div class="default-layout">
<h1>Default Layout</h1>
<slot />
</div>
</template>
<style>
.default-layout {
color: red;
}
</style>
第三方库与模块
Nuxt 在样式方面没有强加任何主观意见,为你提供了广泛的选择。你可以使用任何你想要的样式工具,例如像 UnoCSS 或 Tailwind CSS 这样流行的库。
社区和 Nuxt 团队开发了大量的 Nuxt 模块,以简化集成过程。你可以在网站的模块部分发现它们。以下是一些可以帮助你快速上手的模块
- UnoCSS:即时按需的原子化 CSS 引擎
- Tailwind CSS:功能类优先的 CSS 框架
- Fontaine:字体度量回退 (Font metric fallback)
- Pinceau:自适应样式框架
- Nuxt UI:现代 Web 应用的 UI 库
- Panda CSS:在构建时生成原子化 CSS 的 CSS-in-JS 引擎
Nuxt 模块开箱即用地为你提供良好的开发体验,但请记住,如果你喜爱的工具没有对应的模块,并不意味着你不能在 Nuxt 中使用它!你可以为自己的项目自行配置它。根据工具的不同,你可能需要使用 Nuxt 插件和/或编写你自己的模块。如果你这样做了,请与社区分享它们!
轻松加载网络字体
你可以使用 Nuxt Google Fonts 模块来加载 Google 字体。
如果你正在使用 UnoCSS,请注意它自带一个 网络字体预设,可以方便地从常见提供商(包括 Google 字体等)加载字体。
高级
过渡
Nuxt 带有与 Vue 相同的 <Transition> 元素,并且还支持实验性的 View Transitions API。
字体高级优化
我们建议使用 Fontaine 来减少你的 CLS。如果你需要更高级的功能,可以考虑创建一个 Nuxt 模块来扩展构建过程或 Nuxt 运行时。
LCP 高级优化
你可以采取以下措施来加速下载你的全局 CSS 文件
- 使用 CDN,使文件在物理上更接近你的用户
- 压缩你的资产,理想情况下使用 Brotli
- 使用 HTTP2/HTTP3 进行传输
- 将你的资产托管在同一个域上(不要使用不同的子域)
如果你使用的是 Cloudflare、Netlify 或 Vercel 等现代平台,其中大部分事情应该会自动为你完成。你可以在 web.dev 上找到 LCP 优化指南。
如果你的所有 CSS 都由 Nuxt 内联,你可以(以实验性方式)完全停止在渲染的 HTML 中引用外部 CSS 文件。你可以通过一个钩子来实现这一点,你可以将其放在模块中或 Nuxt 配置文件中。
export default defineNuxtConfig({
hooks: {
'build:manifest': (manifest) => {
// find the app entry, css list
const css = Object.values(manifest).find(options => options.isEntry)?.css
if (css) {
// start from the end of the array and go to the beginning
for (let i = css.length - 1; i >= 0; i--) {
// if it starts with 'entry', remove it from the list
if (css[i].startsWith('entry')) {
css.splice(i, 1)
}
}
}
},
},
})